+ All Categories
Home > Documents > DyPy Documentation · 2019. 4. 2. · DyPy Documentation, Release 0.1 Parameters • filename...

DyPy Documentation · 2019. 4. 2. · DyPy Documentation, Release 0.1 Parameters • filename...

Date post: 30-Sep-2020
Category:
Upload: others
View: 2 times
Download: 0 times
Share this document with a friend
31
DyPy Documentation Release 0.1 Nicolas Piaget Nov 02, 2018
Transcript
Page 1: DyPy Documentation · 2019. 4. 2. · DyPy Documentation, Release 0.1 Parameters • filename (string) – path to a netCDF file • variables (list or string) – variables to read

DyPy DocumentationRelease 0.1

Nicolas Piaget

Nov 02, 2018

Page 2: DyPy Documentation · 2019. 4. 2. · DyPy Documentation, Release 0.1 Parameters • filename (string) – path to a netCDF file • variables (list or string) – variables to read
Page 3: DyPy Documentation · 2019. 4. 2. · DyPy Documentation, Release 0.1 Parameters • filename (string) – path to a netCDF file • variables (list or string) – variables to read

Contents

1 Introduction 31.1 lagranto package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.2 netcdf package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41.3 plotting package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51.4 small tools package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81.5 soundings package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111.6 constants package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121.7 intergrid package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121.8 tools package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

2 Tutorial 152.1 Cross-section . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152.2 Lagranto . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

3 Installation 213.1 Using pip . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

4 Indices and tables 23

Python Module Index 25

i

Page 4: DyPy Documentation · 2019. 4. 2. · DyPy Documentation, Release 0.1 Parameters • filename (string) – path to a netCDF file • variables (list or string) – variables to read

ii

Page 5: DyPy Documentation · 2019. 4. 2. · DyPy Documentation, Release 0.1 Parameters • filename (string) – path to a netCDF file • variables (list or string) – variables to read

DyPy Documentation, Release 0.1

Contents:

Contents 1

Page 6: DyPy Documentation · 2019. 4. 2. · DyPy Documentation, Release 0.1 Parameters • filename (string) – path to a netCDF file • variables (list or string) – variables to read

DyPy Documentation, Release 0.1

2 Contents

Page 7: DyPy Documentation · 2019. 4. 2. · DyPy Documentation, Release 0.1 Parameters • filename (string) – path to a netCDF file • variables (list or string) – variables to read

CHAPTER 1

Introduction

The aim of the DyPy package is to wrap tools used daily in the group. The package is divided in several subpack-ages.

1.1 lagranto package

Based on :

https://lagranto.readthedocs.io/en/latest/

1.1.1 Examples

In a first step, let’s simply read the trajectories:

>>> from dypy.lagranto import Tra>>> filename = 'lsl_20110123_10'>>> trajs = Tra()>>> trajs.load_ascii(filename)

or to read a netcdf file:

>>> filename = 'lsl_20110123_10.4'>>> trajs.load_netcdf(filename)

The proprieties of the trajectories can be shown as follow:

>>> print(trajs)24 trajectories with 41 time steps.Available fields: time/lon/lat/p/Q/RH/TH/BLHtotal duration: -14400.0 minutes>>> print(trajs.variables())['time', 'lon', 'lat', 'p', 'Q', 'RH', 'TH', 'BLH']>>> print(trajs['Q'].shape)(24, 41)

3

Page 8: DyPy Documentation · 2019. 4. 2. · DyPy Documentation, Release 0.1 Parameters • filename (string) – path to a netCDF file • variables (list or string) – variables to read

DyPy Documentation, Release 0.1

1.2 netcdf package

This module is a wrapper for the netCDF4 library. It aims at shorten the reading of netcdf file.

1.2.1 Examples

Let’s start with reading one or several variables:

>>> import dypy.netcdf as dn>>> filename = 'foo.nc'

To display the variables of the netcdf file:

>>> print(dn.read_variables(filename))[u'time', u'lon', u'lat', u'p', u'QV', u'TH', u'BLH']

You can read a single variable (becarful, do not forget the “,” after the variable name):

>>> qv, = dn.read_var(filename, 'QV')

Or you can read several variables in once:

>>> th, qv = dn.read_var(filename, ['TH', 'QV'])

1.2.2 DocStrings

Module to read and write netcdf file.

Interface to netCDF4

dypy.netcdf.addvar(ncfile, varname, vardata, dimensions, attributes=None)Add a variable to an opened netcdf file

dypy.netcdf.addvar_to_file(filename, varname, vardata, dimensions, attributes=None)Add a variable to a netcdf file

dypy.netcdf.create(outname, dimensions, gattributes, format=’NETCDF3_CLASSIC’)create a netCDF

dypy.netcdf.read_dimensions(filename)Read dimensions

Unlimited dimensions size are return as None

Parameters filename (string) –

Returns a dictionary with name as key and the dimension as value

Return type dictionary

dypy.netcdf.read_gattributes(filename)Read global attributes from a netCDF

Parameters filename (string) – path to a netcdf file

Returns global attributes

Return type dictionary

dypy.netcdf.read_var(filename, variables, index=slice(None, None, None), **kwargs)Extract variables from a netCDF

Raise an IOerror if the file[s] is not found; netcdf time are return as datetime array if possible

4 Chapter 1. Introduction

Page 9: DyPy Documentation · 2019. 4. 2. · DyPy Documentation, Release 0.1 Parameters • filename (string) – path to a netCDF file • variables (list or string) – variables to read

DyPy Documentation, Release 0.1

Parameters

• filename (string) – path to a netCDF file

• variables (list or string) – variables to read as a list of string; a single vari-able can also be given as a string

• index (slice, optional) – A slice object; for example np.s_[0, :, 10]

• kwargs (keyword arguments) – A list of arguments to pass to the MFDatasetclass. For example to aggregate the files on the <time> dimension use aggdim=’time’

Returns list of numpy array

Return type list

dypy.netcdf.read_var_attributes(filename, var)Return the attributes of the variables as a dictionary

dypy.netcdf.read_var_bbox(filename, variables, bbox, lon=’lon’, lat=’lat’, return_index=False)Read var only in the bbox

Similar to read_var but read only the data in the given bounding box.

Parameters

• filename (list or string) – filename(s) where the data is located

• variables (list or string) – variable(s) name of the data to read from file

• bbox (list) – coordinates of the bounding box as: minlon, maxlon, minlat, maxlat

• lon (string or np.ndarray, default lon) – name of the 2D longitudearray in the data; or 2D longitude array

• lat (string or np.ndarray, default lat) – name of the 2D latitude ar-ray in the data: or 2D latitude array

• return_index (boolean, default False) –

If True return the index used to reduce the variable data, with the dimension(time, height, lon, lat)

Returns

• bbox_lon (numpy array) – lon restricted to the bbox

• bbox_lat (numpy array) – lat restricted to the bbox

• bbox_dta (numpy arra) – data restricted to the bbox

dypy.netcdf.read_variables(filename)Read variables

Parameters filename (string) –

Returns a list of variables names

Return type list

1.3 plotting package

This module contains mainly a class Mapfigure, which makes it easier to create Basemap plot and add a methodto plots trajectories on top of it.

1.3. plotting package 5

Page 10: DyPy Documentation · 2019. 4. 2. · DyPy Documentation, Release 0.1 Parameters • filename (string) – path to a netCDF file • variables (list or string) – variables to read

DyPy Documentation, Release 0.1

1.3.1 Examples

First let’s load the class:

>>> from dypy.plotting import Mapfigure

Then prepare a map you have two main options:

1. with a domain definition:

>>> domain = [5, 10, 45, 47]>>> m = Mapfigure(domain=domain)

2. Or with lon, lat coordinates:

>>> m = Mapfigure(lon=lon, lat=lat)

In this case, the domain is based on the boundary values of the lon, lat arrays.

The next step is to plot data on the map:

>>> m.contourf(lon, lat, data)

or, if m was prepared using option 2:

>>> m.contourf(m.x, m.y, data)

To add the map background (countries and coastlines):

>>> m.drawmap(nbrem=1, nbrep=1)

where nbrem and nbrep can be specified to adjust the grid lines

Plotting trajectories

To plot trajectories on top of a map, you can do the following:

>>> from dypy.lagranto import Tra>>> trajs = Tra()>>> trajs.load_netcdf(filename)>>> m.plot_traj(trajs, 'QV', cm='Spectral',

levels=np.arange(1, 12, 1))

6 Chapter 1. Introduction

Page 11: DyPy Documentation · 2019. 4. 2. · DyPy Documentation, Release 0.1 Parameters • filename (string) – path to a netCDF file • variables (list or string) – variables to read

DyPy Documentation, Release 0.1

1.3.2 Docstrings

class dypy.plotting.plotting.Mapfigure(resolution=’i’, projection=’cyl’, domain=None,lon=None, lat=None, basemap=None,**kwargs)

Class based on Basemap with additional functionality such as plot_trajectories

drawmap(continent=False, nbrem=5, nbrep=5, coastargs={}, countryargs={}, meridiansargs={},parallelsargs={})

draw basic features on the map nbrem: interval bewteen meridians nbrep: interval between parallels

plot_traj(trajs, variable, cmap=’Spectral’, levels=None, **kwargs)Plot trajectories on a map

Usage: m = Mapfigure(domain=[5, 15, 40, 50]) m.drawmap() m.plot_traj(trajs, ‘QV’)

class dypy.plotting.plotting.SkewT(ax, prange={’dp’: 1.0, ’pbot’: 1000.0, ’ptop’:100.0})

Create a skewT-logP diagramm

es(T)Returns saturation vapor pressure (Pascal) at temperature T (Celsius) Formula 2.17 in Rogers&Yau

gamma_s(T, p)Calculates moist adiabatic lapse rate for T (Celsius) and p (Pa) Note: We calculate dT/dp, not dT/dzSee formula 3.16 in Rogers&Yau for dT/dz, but this must be combined with the dry adiabatic lapserate (gamma = g/cp) and the inverse of the hydrostatic equation (dz/dp = -RT/pg)

1.3. plotting package 7

Page 12: DyPy Documentation · 2019. 4. 2. · DyPy Documentation, Release 0.1 Parameters • filename (string) – path to a netCDF file • variables (list or string) – variables to read

DyPy Documentation, Release 0.1

1.4 small tools package

1.4.1 DocStrings

class dypy.small_tools.CrossSection(variables, coo, pressure, int2p=False, int2z=False,flip=False, pollon=-170, pollat=43, nbre=1000, or-der=1, version=’rotated’)

Create a cross-section

return the distance, the pressure levels, and the variables.

Parameters

• variables (dictionary) – A dictionary of the variables with the following struc-ture: {‘name’: np.array}. If version is rotated: need to contain as least rlon, rlat ifversion is regular: need to contain at least lon, lat

• coo (list or numpy.ndarray) – If coo is a list of coordinates, it is used of thestarting and end points: [(startlon, startlat), (endlon, endlat)] If coo is a numpy.ndarrayit is used as the cross-section points. coo need then to be similar to : np.array([[10, 45],[11, 46], [12, 47]])

• pressure (np.array) – pressure coordinate as 1D array

• int2p (bool, optional (default: False)) – True if variables need tobe interpolated on pressure levels, requires p in the variables, the levels are given bypressure

• int2z (bool, optional (default: False)) – True if variables need to beinterpolated on heights levels, requires z in the variables, the levels are given by pressuremay require ‘flip‘=True

• flip (bool, optional (default: False)) – True if variables need to beflip vertically, the first dimension of 3D array will be flipped

• pollon (float, optional (default: -170)) – pole_longitude of the ro-tated grid

• pollat (float, optional (default: 43)) – pole_latitude of the rotatedgrid

• nbre (int, optional (default: 10000)) – nbre of points along the cross-section

• order ({1, 2, 3, 4}, optional (default: 1)) – order of interpolationsee for details

• version (string (defautl rotated)) – type of grid used as input (rotatedor regular)

dypy.small_tools.interpolate(data, grid, interplevels)interpolate data on grid for given interplevels

Interpolate the data array at every given levels (interplevels) using the grid array as reference.

The grid array need to be increasing along the first axis. Therefore ERA-Interim pressure must be flip:p[::-1, . . . ], but not COSMO pressure since its level 0 is located at the top of the atmosphere.

Parameters

• data (array (nz, nlat, nlon)) – data to interpolate

• grid (array (nz, nlat, nlon)) – grid use to perform the interpolation

• interplevels (list, array) – list of the new vertical levels, in the same unitas the grid

Returns interpolated array

8 Chapter 1. Introduction

Page 13: DyPy Documentation · 2019. 4. 2. · DyPy Documentation, Release 0.1 Parameters • filename (string) – path to a netCDF file • variables (list or string) – variables to read

DyPy Documentation, Release 0.1

Return type array (len(interplevels), nlat, nlon)

Examples

>>> print(qv.shape)(60, 181, 361)>>> print(p.shape)(60, 181, 361)>>> levels = np.arange(200, 1050, 50)(17,)>>> qv_int = interpolate(qv, p, levels)>>> print(qv_int.shape)(17, 181, 361)

dypy.small_tools.rotate_points(pole_longitude, pole_latitude, lon, lat, direction=’n2r’)Rotate lon, lat from/to a rotated system

Parameters

• pole_longitude (float) – longitudinal coordinate of the rotated pole

• pole_latitude (float) – latitudinal coordinate of the rotated pole

• lon (array (1d)) – longitudinal coordinates to rotate

• lat (array (1d)) – latitudinal coordinates to rotate

• direction (string, optional) – direction of the rotation; n2r: from non-rotated to rotated (default) r2n: from rotated to non-rotated

Returns

• rlon (array)

• rlat (array)

dypy.small_tools.dewpoint(p, qv)Calculate the dew point temperature

following (eq.8): Lawrence, M.G., 2005. The Relationship between Relative Humidity and the DewpointTemperature in Moist Air: A Simple Conversion and Applications. Bulletin of the American MeteorologicalSociety 86, 225–233. doi:10.1175/BAMS-86-2-225

Parameters

• p (float, array) – pressure in Pa

• qv (float, array) – specific humidity in kg/kg

Returns dewpoint (in °C)

Return type float, array

dypy.small_tools.esat(t)Calculate the saturation vapor pressure for t in °C

Following eq. 6 of Lawrence, M.G., 2005. The Relationship between Relative Humidity and the DewpointTemperature in Moist Air: A Simple Conversion and Applications. Bulletin of the American MeteorologicalSociety 86, 225–233. doi:10.1175/BAMS-86-2-225

Parameters t (float, numpy.array) – temperature in K

Examples

>>> esat(0)610.94000000000005

1.4. small tools package 9

Page 14: DyPy Documentation · 2019. 4. 2. · DyPy Documentation, Release 0.1 Parameters • filename (string) – path to a netCDF file • variables (list or string) – variables to read

DyPy Documentation, Release 0.1

dypy.small_tools.moist_lapse(t, p)Calculates moist adiabatic lapse rate

Note: We calculate dT/dp, not dT/dz See formula 3.16 in Rogers&Yau for dT/dz, but this must be combinedwith the dry adiabatic lapse rate (gamma = g/cp) and the inverse of the hydrostatic equation (dz/dp = -RT/pg)

Parameters

• t (float, array) – temperature in degree Celsius

• p (float, array) – temperature in Pa

Returns moist adiabatic lapse rate

Return type float, array

dypy.small_tools.equivalent_pot_temp(t, p, qv)Return the equivalent potential temperature in K

computation of equivalent potential temperature according to Bolton (1980) except constant 0.1998 (4.805according to Bolton).

Parameters

• t (np.array, np.float) – Temperature in K

• p (np.array, np.float) – Pressure in hPa

• qv (np.array, np.float) – Specific humidity in kg/kg

Returns THE (equivalent potential temperature in K)

Return type (np.array, np.float)

Examples

>>> t = 16 + 273>>> qv = 0.01156>>> p = 850>>> equivalent_pot_temp(t, p, qv)337.59612858187029

dypy.small_tools.mask_polygon(polygon, array, lon, lat)Mask value outside polygon, work only for regular grid

Parameters

• polygon (array (X x 2)) – coordinates of the polygon

• array (array (nlon x nlat)) – array to mask

• lon (array (nlon x nlat)) – regular coordinates of the array

• lat (array (nlon x nlat)) – regular coordinates of the array

Returns masked array

Return type MaskedArray (nlon x nlat)

Examples

>>> import numpy as np>>> polygon = np.array([[5, 5],>>> [10, 5],>>> [10, 10],>>> [5, 10],>>> [5, 5]])

(continues on next page)

10 Chapter 1. Introduction

Page 15: DyPy Documentation · 2019. 4. 2. · DyPy Documentation, Release 0.1 Parameters • filename (string) – path to a netCDF file • variables (list or string) – variables to read

DyPy Documentation, Release 0.1

(continued from previous page)

>>> array = np.zeros((20, 20))>>> lon = np.arange(0, 20, dtype=float)>>> lat = np.arange(0, 20, dtype=float)>>> lons, lats = np.meshgrid(lon, lat)>>> clipped = mask_polygon(polygon, array, lons, lats)

dypy.small_tools.potential_temperature(t, p, p0=1000)Calculate the potential temperature

Parameters

• t (array) – temperature in K

• p (array) – pressure in hPa

• p0 (float, optional) – pressure at sea level in hPa

Returns potential temperature

Return type array

dypy.small_tools.great_circle_distance(lon1, lat1, lon2, lat2)Calculate the great circle distance between two points

based on : https://gist.github.com/gabesmed/1826175

Parameters

• lon1 (float) – longitude of the starting point

• lat1 (float) – latitude of the starting point

• lon2 (float) – longitude of the ending point

• lat2 (float) – latitude of the ending point

Returns distance (km)

Return type float

Examples

>>> great_circle_distance(0, 55, 8, 45.5)1199.3240879770135

dypy.small_tools.read_shapefile(shapefile)Return the geometry (list) of each shape and the projection

Parameters shapefile (string) – path to a shapefile

Returns

• geometries (list of array (number of points, 2))

• projection (projection string (PROJ4.strings))

1.5 soundings package

dypy.soundings.create_sounding_url(station, year, month, day, hour)create the url to acces sounding based on the University of Wyoming website (http://weather.uwyo.edu/upperair/sounding.html)

usage: create_url(‘06610’, 1993, 12, 12, 12)

Parameters

1.5. soundings package 11

Page 16: DyPy Documentation · 2019. 4. 2. · DyPy Documentation, Release 0.1 Parameters • filename (string) – path to a netCDF file • variables (list or string) – variables to read

DyPy Documentation, Release 0.1

• station (string) – Number of the station 10410 Essen (D) 10618 Idar-Oberstein(D) 07145 Trappes (F) 06260 De Bilt (NL) 10238 Bergen (D) 06610 Payerne (CH)16080 Milan (I) 10868 Munich (D)

• year (float) – yyyy

• month (float) – mm

• day (float,) – dd

• hour (float) – hh

Returns The URL as string

Return type string

dypy.soundings.get_sounding(file_or_url)

input:

file_or_url (string): the name of the sounding file or the URL of the sounding file

output: sounding (dictionary): dictionary containing the sounding data

1.6 constants package

1.7 intergrid package

class dypy.intergrid.Intergrid(griddata, lo, hi, maps=[], copy=True, verbose=True, or-der=1, prefilter=False)

interpolate data given on an Nd rectangular grid, uniform or non-uniform.

documentation and original website: https://denis-bz.github.io/docs/intergrid.html

Purpose: extend the fast N-dimensional interpolator scipy.ndimage.map_coordinates to non-uniform grids,using np.interp.

Background: please look at http://en.wikipedia.org/wiki/Bilinear_interpolation http://stackoverflow.com/questions/6238250/multivariate-spline-interpolation-in-python-scipy http://docs.scipy.org/doc/scipy-dev/reference/generated/scipy.ndimage.interpolation.map_coordinates.html

Parameters

• griddata (numpy array_like,) – 2d 3d 4d . . .

• lo (numpy array_like,) –

• hi (numpy array_like,) – user coordinates of the corners of griddata, 1d array-like, lo < hi

• maps (list) – a list of dim descriptors of piecewise-linear or nonlinear maps, e.g.[[50, 52, 62, 63], None] # uniformize lat, linear lon

• copy (bool, default True;) – make a copy of query_points copy=False over-writes query_points, runs in less memory

• verbose (bool, default True) – print a 1-line summary for each call, with runtime

• order (int, default 1) – see map_coordinates

• prefilter (bool, default False) – the default: smoothing B-spline 1 orTrue: exact-fit interpolating spline (IIR, not C-R) 1/3: Mitchell-Netravali spline, 1/3B + 2/3 fit (prefilter is only for order > 1, since order = 1 interpolates)

12 Chapter 1. Introduction

Page 17: DyPy Documentation · 2019. 4. 2. · DyPy Documentation, Release 0.1 Parameters • filename (string) – path to a netCDF file • variables (list or string) – variables to read

DyPy Documentation, Release 0.1

Examples

1) For regular grid: Say we have rainfall on a 4 x 5 grid of rectangles, lat 52 .. 55 x lon -10 .. -6, andwant to interpolate (estimate) rainfall at 1000 query points in between the grid points.

Define the grid

>>> griddata = np.loadtxt(...) # griddata.shape == (4, 5)>>> lo = np.array([ 52, -10 ]) # lowest lat, lowest lon>>> hi = np.array([ 55, -6 ]) # highest lat, highest lon

Set up an interpolator function “interfunc()” with class Intergrid

>>> interfunc = Intergrid( griddata, lo=lo, hi=hi )

Generate 1000 random query points, lo <= [lat, lon] <= hi

>>> query_points = lo + np.random.uniform( size=(1000, 2) ) * (hi -→˓lo)

Get rainfall at the 1000 query points

>>> query_values = interfunc( query_points ) # -> 1000 values

What this does:

for each [lat, lon] in query_points:

1) find the square of griddata it’s in, e.g. [52.5, -8.1] -> [0, 3] [0, 4] [1, 4] [1, 3]

2) do bilinear (multilinear) interpolation in that square, usingscipy.ndimage.map_coordinates .

Check: interfunc( lo ) -> griddata[0, 0], interfunc( hi ) -> griddata[-1, -1] i.e. griddata[3, 4]

2) For non-uniform rectangular grids: What if our griddata above is at non-uniformly-spaced lati-tudes, say [50, 52, 62, 63] ? Intergrid can “uniformize” these before interpolation, like this:

>>> lo = np.array([ 50, -10 ])>>> hi = np.array([ 60, -6 ])>>> maps = [[50, 52, 62, 63], None] # uniformize lat, linear lon>>> interfunc = Intergrid( griddata, lo=lo, hi=hi, maps=maps )

This will map (transform, stretch, warp) the lats in query_points column 0 to array coordinatesin the range 0 .. 3, using np.interp to do piecewise-linear (PWL) mapping:

>>> 50 51 52 53 54 55 56 57 58 59 60 61 62 63 # lo[0]→˓.. hi[0]>>> 0 .5 1 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2 3

maps[1] None says to map the lons in query_points column 1 linearly: -10 -9 -8 -7 -6 # lo[1].. hi[1] 0 1 2 3 4

More doc: https://denis-bz.github.com/docs/intergrid.html

at(X, out=None)query_values = Intergrid(. . . ) ( query_points npt x dim )

1.8 tools package

module with wrappers for dyntools

1.8. tools package 13

Page 18: DyPy Documentation · 2019. 4. 2. · DyPy Documentation, Release 0.1 Parameters • filename (string) – path to a netCDF file • variables (list or string) – variables to read

DyPy Documentation, Release 0.1

exception dypy.tools.dyntools.DynToolsExceptionRaise this when a dyn_tools call fails

14 Chapter 1. Introduction

Page 19: DyPy Documentation · 2019. 4. 2. · DyPy Documentation, Release 0.1 Parameters • filename (string) – path to a netCDF file • variables (list or string) – variables to read

CHAPTER 2

Tutorial

This tutorial aims at giving a rapid overview of the usage of the DyPy module.

It covers the following topics:

2.1 Cross-section

The goal is to create a cross-section using COSMO data. The data will be loaded from a NetCDF file. In order toreduce the amount of data loaded, we will only load the data from the bounding box of the cross-section.

2.1.1 Parameters

Here we define the variables that we will read, the coordinates of the cross-section, as ((startlon, startlat), (endlon,endlat)), and the pressure coordinates of the cross-section:

>>> filename = 'lffd2000101302.nc'>>> cstfile = 'lffd2000101300c.nc'>>> variables = ['QV', 'T', 'P', 'PS]>>> coos = ((8, 45), (8, 48))>>> pressure = np.arange(200, 1010, 10)

2.1.2 Read the data

First we read the coordinates of the rotated grid from the constant file:

>>> rlon, rlat = read_var(cstfile, ['rlon', 'rlat'])

Then we can read the variables from within the bounding box, as well as the coordinates of the bounding box grid.The index of the bounding box grid points are saved as well to reduce later rlon, rlat and others to the boundingbox grid:

>>> lon, lat, qv, t, p, ps, index = read_var_bbox(filename, variables,(7.5, 8.5, 44.8, 48.1),return_index=True)

15

Page 20: DyPy Documentation · 2019. 4. 2. · DyPy Documentation, Release 0.1 Parameters • filename (string) – path to a netCDF file • variables (list or string) – variables to read

DyPy Documentation, Release 0.1

2.1.3 Create the cross-section

We are now ready to define the cross-section, for this we will use the CrossSection class from the small toolspackage:

>>> from dypy.small_tools import CrossSection

The docstring (help) of the class can be found here dypy.small_tools.CrossSection It shows that theclass need at least three arguments, a dictionary of variables, the coordinates of the cross-section, and the verticalcoordinates of the cross-section. The last two are already defined, we just need to define the dictionary of variables:

>>> variables = {'qv': qv * 1000,'t': t,'p': p / 100,'rlon': rlon[index[-1]],'rlat': rlat[index[-2]],'ps': ps / 100}

We can now define the cross-section, using one extra optional argument. The switch int2p can be used if thevariables need to be interpolated on pressure levels:

>>> cross = CrossSection(variables, coos, pressure, int2p=True)

Note: The CrossSection class has predefined values for pollon and pollat. Make sure to set them to your ownsetting if you are using the rotated version (default):

>>> CrossSection(pollon=-170, pollat=62)

2.1.4 Create the plot

First, we need to create the grid on which to plot using here the latitude (along the cross-section) and the pressurecoordinates:

>>> x, zi = np.meshgrid(cross.lat, cross.pressure)

Then, we can create the plot, using PS for plotting the topography:

>>> fig, ax = plt.subplots()>>> ax.set_ylim(ymin=500, ymax=1000)>>> ax.invert_yaxis()>>> cf = ax.contourf(x, zi, cross.qv, levels=np.arange(1, 8, 0.5), extend='both',→˓cmap='Blues')>>> cb = fig.colorbar(cf)>>> cb.set_label('qv')>>> ct = ax.contour(x, zi, cross.t, levels=[-10, 0, 5], colors='k', linestyles=→˓'solid')>>> ct.clabel(fmt='%1.0f')>>> ax.fill_between(cross.lat, 1000, cross.ps, color='grey')

16 Chapter 2. Tutorial

Page 21: DyPy Documentation · 2019. 4. 2. · DyPy Documentation, Release 0.1 Parameters • filename (string) – path to a netCDF file • variables (list or string) – variables to read

DyPy Documentation, Release 0.1

2.1.5 Using height as vertical coordinate

We can define a similar cross-ection but using height as vertical coordinates. For this we need to read HHL andHSURF from the constant file.:

>>>> hhl, hsurf = read_var(cstfile, ['HHL', 'HSURF'])>>> z = (hhl[1:, ...] + hhl[:-1, ...]) / 2

We add them to the variables dictionary, and change the vertical coordinates of the cross-section:

>>> variables['z'] = z[index[1:]]>>> variables['hsurf'] = hsurf[index[2:]]>>> heights = np.arange(0, 10000, 100)

We can know create the cross-section, using now the optional arguments int2z (the z variable is required) and flip(we need monotically increasing data):

>>> cross = CrossSection(variables, coos, heights, int2z=True, flip=True)

We can know define the plot as follow:

>>> x, zi = np.meshgrid(cross.lat, cross.pressure)>>> fig, ax = plt.subplots()>>> ax.set_ylim(ymin=0, ymax=5000)>>> cf = ax.contourf(x, zi, cross.qv, levels=np.arange(1, 8, 0.5), extend='both',→˓cmap='Blues')>>> cb = fig.colorbar(cf)>>> cb.set_label('qv')>>> ct = ax.contour(x, zi, cross.t, levels=[-10, 0, 5], colors='k', linestyles=→˓'solid')>>> ct.clabel(fmt='%1.0f')>>> ax.fill_between(cross.lat, 0, cross.hsurf, color='grey')

2.1. Cross-section 17

Page 22: DyPy Documentation · 2019. 4. 2. · DyPy Documentation, Release 0.1 Parameters • filename (string) – path to a netCDF file • variables (list or string) – variables to read

DyPy Documentation, Release 0.1

2.2 Lagranto

The goal of this section is show how to calculate trajectories, analyzed them and plot them using the lagrantopackage.

• Calculation

• Analyze

• Plotting

• Writing

2.2.1 Calculation

The lagranto package provide a class, dypy.lagranto.LagrantoRun, to wrap the Lagranto programs inpython. It allow to calculate trajectories in parallel. You can take a look at the docstring to get familiar with theclass.

Let’s say that we want to calculate Warm Conveyor Belt trajectories for a 5 day period in June 2013. UsingEra-Interim we can start trajectories every 6 hour and we will calculate them for 48 hours forward in time. Sincedypy.lagranto.LagrantoRun needs a list of (startdate, enddate), we can build the dates as follow:

from datetime import datetime, timedeltafrom dypy.small_tools import intervalstartdate = datetime(2013, 6, 1, 0)enddate = startdate + timedelta(days=5)dates = [(d, d + timedelta(hours=48)) for d in

interval(startdate, enddate, timedelta(hours=6))]

If the Era-interim data are in the erainterim folder and if the output files should be written in the output folder,then the dypy.lagranto.LagrantoRun can be initialized as follow:

from dypy.lagranto import LagrantoRunlrun = LagrantoRun(dates, workingdir='erainterim',

outputdir='output', version='ecmwf')

18 Chapter 2. Tutorial

Page 23: DyPy Documentation · 2019. 4. 2. · DyPy Documentation, Release 0.1 Parameters • filename (string) – path to a netCDF file • variables (list or string) – variables to read

DyPy Documentation, Release 0.1

We want to start the trajectories every 20km in the box [5E, 40E, 30N, 60N], so let’s create a starting file:

specifier = "'box.eqd(5,20,40,50,20)@profile(850,500,10)@hPa'"out_create_startf = lrun.create_startf(startdate, specifier, tolist=True)

The tolist argument is needed if we want to use the same staring file for all starting time of the trajectories. Wecan now calculate the trajectories, but first starting for a single date to test our setup:

out_caltra = lrun.caltra(*dates[1])

We can also test tracing Q along a trajectories:

out_trace = lrun.trace(dates[1][0], field='Q 1.')

We can now calculate and trace the trajectories in parallel, but for this we will use a tracevars file:

tracevars = """Q 1. 0 PU 1. 0 P"""out = lrun.run_parallel(trace_kw={'tracevars_content': tracevars}, type='both')

The tracevars_content keyword argument will be passed to trace to create a tracevars file with Q and U. The typekeyword argument determine what is run in parallel, currently both, trace, and caltra are available.

2.2.2 Analyze

Now that we have calculated trajectories let’s read them and analyze them. By default the name of the files areformatted as lsl_{:%Y%m%d%H}.4. So if we want to read the trajectories started at 00 UTC 01 June 2013 we cando as follow:

from dypy.lagranto import Trafilename_template = 'output/lsl_{:%Y%m%d%H}.4'filename = filename_template.format(date=dates[-1][0])trajs = Tra()trajs.load_netcdf(filename)print(trajs)

We can now test if the trajectories fulfill the standard criteria for WCB, an ascent greater than 500 hPa in 48 hours.To make it clear, the goal of this exmple is not to replace the fortran routines of the LAGRANTO package but toillustrate the possibilities that python provides to analyze trajectories using a simple example.

wcb_index = np.where((trajs['p'][:, :1] - trajs['p']) > 500)wcb_trajs = Tra()wcb_trajs.set_array(trajs[wcb_index[0], :])print(wcb_trajs)

2.2.3 Plotting

Now that we have WCB trajectories, let’s plot them on a map. We will use cartopy for this.

import cartopy.crs as ccrsimport cartopy.feature as cfeaturefrom dypy.plotting import plot_trajsimport matplotlib.pyplot as plt

crs = ccrs.Stereographic(central_longitude=180 - 170,central_latitude=90 - 43,true_scale_latitude=90 - 43)

fig = plt.figure()

(continues on next page)

2.2. Lagranto 19

Page 24: DyPy Documentation · 2019. 4. 2. · DyPy Documentation, Release 0.1 Parameters • filename (string) – path to a netCDF file • variables (list or string) – variables to read

DyPy Documentation, Release 0.1

(continued from previous page)

ax = plt.axes(projection=crs)land_50m = cfeature.NaturalEarthFeature('cultural', 'admin_0_countries',

'50m', edgecolor='gray',facecolor='none', linewidth=0)

ax.add_feature(land_50m)ax.set_extent([-10, 28, 30, 60])plot_trajs(ax, wcb_trajs, 'p')# fig.savefig('wcb_trajs_{date:%Y%m%d_%H}.pdf'.format(date=dates[-1][0]), bbox_→˓inches='tight')

2.2.4 Writing

The WCB trajectories can also be written to disk as follow:

wcb_trajs.write_netcdf('output/wcb_trajs.nc')

20 Chapter 2. Tutorial

Page 25: DyPy Documentation · 2019. 4. 2. · DyPy Documentation, Release 0.1 Parameters • filename (string) – path to a netCDF file • variables (list or string) – variables to read

CHAPTER 3

Installation

3.1 Using pip

Ideally install it in a virtual environment. See for example venv.

pip install git+https://git.iac.ethz.ch/atmosdyn/DyPy.git --process-dependency-→˓links

Then you can install the dependencies for testing or the documentations as follow:

pip install DyPy[testing]pip install DyPy[docs]

To build the documentation do the following:

cd /path/to/dypy/locationcd docsmake html

To test the package do the following:

cd /path/to/dpyp/locationpytest

21

Page 26: DyPy Documentation · 2019. 4. 2. · DyPy Documentation, Release 0.1 Parameters • filename (string) – path to a netCDF file • variables (list or string) – variables to read

DyPy Documentation, Release 0.1

22 Chapter 3. Installation

Page 27: DyPy Documentation · 2019. 4. 2. · DyPy Documentation, Release 0.1 Parameters • filename (string) – path to a netCDF file • variables (list or string) – variables to read

CHAPTER 4

Indices and tables

• genindex

• modindex

• search

23

Page 28: DyPy Documentation · 2019. 4. 2. · DyPy Documentation, Release 0.1 Parameters • filename (string) – path to a netCDF file • variables (list or string) – variables to read

DyPy Documentation, Release 0.1

24 Chapter 4. Indices and tables

Page 29: DyPy Documentation · 2019. 4. 2. · DyPy Documentation, Release 0.1 Parameters • filename (string) – path to a netCDF file • variables (list or string) – variables to read

Python Module Index

ddypy.constants, 12dypy.intergrid, 12dypy.netcdf, 4dypy.plotting.plotting, 7dypy.small_tools, 8dypy.soundings, 11dypy.tools.dyntools, 13

25

Page 30: DyPy Documentation · 2019. 4. 2. · DyPy Documentation, Release 0.1 Parameters • filename (string) – path to a netCDF file • variables (list or string) – variables to read

DyPy Documentation, Release 0.1

26 Python Module Index

Page 31: DyPy Documentation · 2019. 4. 2. · DyPy Documentation, Release 0.1 Parameters • filename (string) – path to a netCDF file • variables (list or string) – variables to read

Index

Aaddvar() (in module dypy.netcdf), 4addvar_to_file() (in module dypy.netcdf), 4at() (dypy.intergrid.Intergrid method), 13

Ccreate() (in module dypy.netcdf), 4create_sounding_url() (in module dypy.soundings), 11CrossSection (class in dypy.small_tools), 8

Ddewpoint() (in module dypy.small_tools), 9drawmap() (dypy.plotting.plotting.Mapfigure method),

7DynToolsException, 13dypy.constants (module), 12dypy.intergrid (module), 12dypy.netcdf (module), 4dypy.plotting.plotting (module), 7dypy.small_tools (module), 8dypy.soundings (module), 11dypy.tools.dyntools (module), 13

Eequivalent_pot_temp() (in module dypy.small_tools),

10es() (dypy.plotting.plotting.SkewT method), 7esat() (in module dypy.small_tools), 9

Ggamma_s() (dypy.plotting.plotting.SkewT method), 7get_sounding() (in module dypy.soundings), 12great_circle_distance() (in module dypy.small_tools),

11

IIntergrid (class in dypy.intergrid), 12interpolate() (in module dypy.small_tools), 8

MMapfigure (class in dypy.plotting.plotting), 7mask_polygon() (in module dypy.small_tools), 10moist_lapse() (in module dypy.small_tools), 9

Pplot_traj() (dypy.plotting.plotting.Mapfigure method), 7potential_temperature() (in module dypy.small_tools),

11

Rread_dimensions() (in module dypy.netcdf), 4read_gattributes() (in module dypy.netcdf), 4read_shapefile() (in module dypy.small_tools), 11read_var() (in module dypy.netcdf), 4read_var_attributes() (in module dypy.netcdf), 5read_var_bbox() (in module dypy.netcdf), 5read_variables() (in module dypy.netcdf), 5rotate_points() (in module dypy.small_tools), 9

SSkewT (class in dypy.plotting.plotting), 7

27


Recommended