Python Wrapper

8 minute read

This documentation describes the python wrapper to test the parametrisation and to create some off-line climatologies. The code is located in the python_wrapper sub folder.

Prerequisites

A working python 2 or python 3 version is required to run the code. You’ll also need a working numpy python package. It is also recommended to have the netCDF4 package available to your python distribution. You will also need the gfrotran and gcc compilers in order to build the python module from the Fortran source files. The compiling process involves the Fortran to C wrapper f2py which comes with the numpy’s distutils package.

Building and Installing

Building and installing is most simple:

$: python setup.py build
$: python setup.py intall

The latter command will install the built python package into the root file system; usually /usr/lib/pythonX.X/site-packages. If you don’t have write access to /usr/lib/ install the packages with the --user option:

$: python setup.py install --user

This will install the packages in $HOME/.local/lib/pythonX.X/site-packages/. With X.X being the python version (e.g 3.6). If this directory doesn’t already exist create it with:

$: mkdir -p $HOME/.local/lib/pythonX.X/site-packages/

You should now be able to import the sea-breeze package:

>>> import seabreezediag as sbd

The Classes

The python package contains a couple of classes which are described here.

The Config class

Read a configuration file and return it’s content stored in a dictionary object.

  • Variables:
    filename (str) : name of the config file to be read
     (2D-array) : Land-sea mask of the model (lat,lon)
    
  • Keywords:
    maketuple (bool)    : if maketuple is True the method tries
                             to interprete values with , as seperators for tuple values
                             (defautl : True)
    skipwhitespace (bool) : whitespaces wont be considered if set True
                             (defautl : True)
    split (str) : the seperator to seperate key and value in the config file
                          (defautl : =)
    

Example:

Consider the following simple configuration file:

$: cat test.conf
#Filen ame of the test data
filename = 'foo.nc' #
variable = bar # The variable to be considered
 x1 = 9.0 # First index
x2 =10  # Last index
update = true
times = 1,2,3 # Some time steps
>>> from seabreezediag.configdir import Config
>>> C = Config('test.conf')
print(C)
Keys     | Values
-------------------------
update   | True
times    | (1.0, 2.0, 3.0)
x2       | 10
filename | foo.nc
variable | bar
x1       | 9.0

The class tries to open the file filename, read it and create a class instance for every key entry

Note: Every key is an instance of Conf but Conf itself is of type dict therefore the instance can be accesses both ways

Example:

>>> T = C['times']
>>> t = C.times
>>> T == t
Ture

The Meta class

The Meta class is not a meta class. It can be used to read important (static) meta data from netcdf-files; like Longitude, Latitude vectors and other data.

The object is created by calling :

from seabreezediag.configdir import Meta,Config
C = Config('path/to/config.conf')
M = Meta(C)

The only variable that Meta is created with has to be of type Config.

Meta has the following instances:

  • lon (1D-array)   : the longitude vector
    lat (1D-array)   : the latitude vector
    start (datetime) : the first date of the considered period
    end (datetime)   : the last date of the considered period
    dates (list)     : list of netcdf file names with data between start and end
    datadir (str)    : the path to the data that should be read
    prefix (str)     : the prefix of the netcdf file names containing the data (like ERAI)
    vp (1D-array)    : the pressure vector
    vv (ND-array)    : the v-wind field
    vu (ND-array)    : the u-wind field
    vtheta (ND-array): the surface temperature field
    

The following methods are available:

Meta.create_nc(fname,varname,times,add=None):

  • Output the seabreeze data into a netcdf-file
    • Variables:
      data (ND-array)  : the data that should be written to a netcdf file
      fname (str)      : the netcdf file name
      varname (str)    : the name of the netcdf variable
      times (1D-array) : the time vector
      add              : suffix for additional information to be added to the netcdf.long_name attribute (dfault : None)
      

Meta.read(varname,timestep=None):

  • This method reads a variable from an opened netcdf file
    • Variables:
      f (netcdf-ojbect)  : object of the netcdf
      varname (str)      : variable name to be read
      timestep (int)     : the time step that should be read, if None the whole array is read (default: None)
      
    • Returns:
      ND-array
  • Note For Meta to work Config needs the following entries:
  • landfracfile : File name of land area fraction (land-sea mask) data
  • topofile : File name of orography data
  • orofile : File name of std of sub-grid orography
  • vlon : Variable name for longitude vector
  • vlat : Variable name for latitude vector
  • start : Start date of the considered period
  • last : End date of the considered period
  • datadir : Parent directory of the netcdf data
  • prefix : Prefix of the netcdf-file names, like ERAI
  • vp : Name of the pressure variable
  • vu : Name of the u-wind variable
  • vv : Name of the v-wind variable
  • vtheta : Name of the surf. temp. variable

    Note: The structure of the netcdf files containing the data to be read should have the following format:

    datadir/YYYY/prefix_YYYY_MM_DD.nc

    for daily data or:

    datadir/YYYY/prefix_YYYY_MM.nc

    for monthly data.

The seabreezediag class

This is the class that does the actual work. It is simply imported by:

>>> import seabreezediag as sbd

The class offers the following methods:

sbd.f2c(array)

  • Convert from column/row major to row/column major. This function has been added, to convert
    • Variables:
      f (netcdf-ojbect)  : object of the netcdf
      array (ND-array)  : array of rank N and any type to be converted
      
    • Returns:
      
      ND-array         : Converted array

sbd.read_nc(fnv, fnu, fntheta, fnci, vv='v', vu='u', vtheta='t2m', vci='ci')

  • Method to read relevant data from various netcdf-sources
    • Variables:
      f (netcdf-ojbect)  : object of the netcdf
      fnv (str)     : name of the v-wind netcdf file
      fnu (str)     : name of the u-wind netcdf file
      fntheta (str) : name of the temp netcdf file
      fnci (str)    : name of the sea-ice frac. netcdf file
      vv (str)      : name of the v-wind netcdf variable (default : v)
      vu (str)      : name of the u-wind netcdf variable (default : u)
      vtheta (str)  : name of the of the surf temp var. (default : t2m)
      vci (str)     : name of the sea-ice variable (default : ci)
      
    • Returns:
      namedtuple         : Named tuple containing all information

      Example:

      >>> e = '~/Data/ERAI/netcdf/1988/Erai_'
      >>> nc_data  = sbd.read_nc(e+'v_1988_09.nc',e+'u_1988_09.nc',
              e+'t2m_1988_09.nc', e+'ci_1988_09.nc')
      

      The returned namedtuple has the following field names:

      >>> print(nc_data._fields)
      >>> ('time', 'pres', 'dt', 'nc', 'v', 'u', 'theta', 'ci')
      
      
      time  : time vector (1d-array)
      pres  : pressure variable object (netcdf-object)
      dt    : model timestep (int)
      nc    : dictionary with all opened netcdf-file objects (dict)
      v     : v-wind variable (netcdf-object)
      u     : u-wind variable object (netcdf-object)
      theta : surf-temp variable object (netcdf-objcet)
      ci    : Sea-ice fract netcdf-variable object (netcdf-object)
      


sbd.diag(tt, lsm, z, std, lon, lat, *args, **kwargs)

  • Method to calculate potential strength of sea-breeze convergence within a predefined coastal area.
    • Variables:
      tt (int)       : Number of timestep since start of application,
                       used to determine the beginning of simulation and and the
                       application of the algorithm in the considered interval
      lsm (2D-array) : Land-sea mask of the model (lat,lon)
      z (2D-array)   : Surface elevation data (lat,lon)
      std (2D-array) : Standard deviation of subgrid orography
      lon (1D-array) : The longitude vector of the model
      lat (1D-array) : The latitude vector of the model
      p (1D-array)   : Pressure levels in Pa stored in a 1D array
      u (ND-array)   : U-component of the wind stored ([time],pres,lat,lon) ,time is optional
      v (ND-array)   : V-component of the wind stored ([time],pres,lat,lon) ,time is optional
      t (ND-array)   : Surface temperature array  ([time],lat,lon), time is optional
      ci (ND-array)  : Fraction of sea-ice cover [0..1] ([time],lat,lon)
                       time is optional. Ci can be set to None, in which case
                       it won't be taken into account for calculation.
      
    • Keywords:
      windspeeed (2D-array)   : Wind speed, passed through the application period (lat,lon)
                                (default: zero array)
      winddir (2D-array)      : Wind direction, passed through the application period (lat,lon)
                                (default: zero array)
      thc (2D-array)          : Thermal heating contrast, passed through the application period (lat,lon)
                                (default: zero array)
      target_plev (float)     : P-level (hPa) for wind thresh application
                                (default: 700.)
      thresh_wind (float)     : Thresh. of wind speed  (m/s)
                                (default: 11.)
      thresh_winddir (float)  : Thresh. of wind speed  change (m/s)
                                (default: 11.)
      thresh_winddir (float)  : Thresh. of wind direction  change (deg.)
                                (default: 90.)
      thresh_windch (float)   : Thresh. of wind speed change (m/s)
                                (default: 5.)
      thresh_thc (float)      : Thresh. of thermal heating contrast (K)
                                (default: 0.75)
      target_time (float)     : Time perid for application of thresholds (h)
                             (default: 6.)
      maxdist (float)         : Area of influence by the sea-breeze on-/offshore (km)
                             (default: 180.)
      timestep (float)      : Time stepping of the model (mins)
                             (default: 24.)
      meta (float)          : If meta is of type namedtuple the arguments
                             for the u-array, v-array, t-array and ci-array are skipped and
                             the data is taken from meta (default: None)
      
    • Returns:
      timestep (int)   : timestep after the application
      breeze (ND-array): sub-grid scale see-breeze convergence ([time],lat,lon)
      thc (2D-array)   : thermal heating contrast of last timestep as initial cond. for next timestep
      ws (2D-array)    : windspeed of last timestep as init. cond. for next timestep
      wd (2D-array)    : wind direction of last timestep as init. for next timestep
      

      Example:

>>> from netCDF4 import Dataset as nc, num2date
>>> import numpy as np
>>> from datetime import datetime, timedelta
>>> import seabreezediag as sbd
>>> tt = 1 #Set the first timestep to one
>>> THC = np.zeros([T.shape[-3],T.shape[-2]])
>>> WS,WD = np.zeros_like(thc),np.zeros_like(thc)
>>> for fn in  ('input_netcdf-month1.nc','input_netcdf-month2.nc'):
        test_nc = nc(fn,'a') #Open the data netcdf-file
        time = num2date(test_nc.variables['time'][:],
        ...                 test_nc.variables['time'].units)
        >>> P = test_nc.variables['pres'][:]
        >>> U = test_nc.variables['uwind'][:]
        >>> V = test_nc.variables['vwind'][:]
        >>> T = test_nc.variables['tsurf'][:]
        >>> LSM = test_nc.variables['lsm'][:]
        >>> CI = test_nc.variables['s_ice'][:]
        >>> H = test_nc.variables['z'][:]
        >>> dt = (time[1] - time[0]).minutes
        >>> tt,breeze,THC,WS,WD = sbd.diag(tt,LSM,H,CI,P,U,V,T,CI,WS,WD,
        ...                                    THC,timestep=dt)
        >>> test_nc.variables['breeze'][:]=breeze
        >>> test_nc.close()

The file test_run.py in the python_wrapper directory provides an example application of the module.

If you are considering implementing this routine take a look at the about section to learn more on how to contribute and improve this project. You are encouraged to get in touch via Git Hub. Bugs should be reported either on the Git Hub issues pages or by sending an email to the author of this page.