pySW4.utils.utils module

Python module with general utilities.

author:Shahar Shani-Kadmiel (s.shanikadmiel@tudelft.nl)
copyright:Shahar Shani-Kadmiel
license:This code is distributed under the terms of the GNU Lesser General Public License, Version 3 (https://www.gnu.org/copyleft/lesser.html)
_list(x)[source]
close_polygon(x, y)[source]

Return a list of points with the first point added to the end.

flatten(ndarray)[source]

Returns a flattened 1Darray from any multidimentional array. This function is recursive and may take a long time on large data.

geographic2cartesian(proj4=None, sw4_default_proj='+proj=latlong +datum=NAD83', lon0=0, lat0=0, az=0, m_per_lat=111319.5, m_per_lon=None, lon=None, lat=None, x=None, y=None)[source]

Calculate SW4 cartesian coordinats from geographic coordinates lon, lat in the proj4 projection. If x, y coordinates are given (x and y are not None) the inverse transformation is performed.

Parameters:

proj4 : str or dict or None

EPSG or Proj4. If EPSG then string should be ‘epsg:number’ where number is the EPSG code. See the Geodetic Parameter Dataset Registry for more information. If Proj4 then either a dictionary:

{'proj': projection, 'datum': 'datum', 'units': units,
 'lon_0': lon0, 'lat_0': lat0, 'scale': scale ... etc.}

or a string:

'+proj=projection +datum=datum +units=units +lon_0=lon0 \
    +lat_0=lat0 +scale=scale ... etc.'

should be given.

See the Proj4 documentation for a list of general Proj4 parameters.

In the context of SW4 this dictionary or string should be taken from the grid line in the SW4 input file.

sw4_default_proj : str

SW4 uses ‘+proj=latlong +datum=NAD83’ as the default projection. Pass a different projection for other purposes. See proj4.

lon0 : float

Longitude of the grid origin in degrees.

This is the lon keyword on the grid line in the SW4 input file.

lat0 : float

Latitude of the grid origin in degrees.

This is the lat keyword on the grid line in the SW4 input file.

az : float

Azimuth between North and the x axis of the SW4 grid.

This is the az keyword on the grid line in the SW4 input file.

m_per_lat : float

How many m to a degree latitude. (default: 111319.5 m)

This is the mlat keyword on the grid line in the SW4 input file.

m_per_lon : float

How many m to a degree longitude. If None, m_per_lat is used).

This is the mlon keyword on the grid line in the SW4 input file.

lon : float

Longitude coordinates in degrees to convert (geo. ===> cart.).

lat : float

Latitude coordinates in degrees to convert (geo. ===> cart.).

x : float

x coordinates in meters to convert (cart. ===> geo.).

y : float

y coordinates in meters to convert (cart. ===> geo.).

Returns:

Converted coordinates:

  • x, y if geo. ===> cart. was invoked or
  • lon, lat if cart. ===> geo. was invoked.
     X
   ⋰
 ⋰
o------->Y
|
|
V
Z

If the azimuth of the SW4 grid is 0 this translates to:

  • X == Northing
  • Y == Easting
  • Z == Vertical (inverted!)
get_corners(x, y)[source]

Extract the corners of the data from its coordinates arrays x and y.

Returns:

2x list

  • one list of longitudes (or x) and
  • another list of latitudes (or y).
line_in_loglog(x, m, b)[source]

Function to calculate the \(y\) values of a line in log-log space according to

\[y(x) = b \cdot 10^{\log_{10} x^m},\]

where:

  • \(m\) is the slope of the line,
  • \(b\) is the \(y(x=1)\) value and
  • \(x\) is a sequence of values on the x-axis.
make_cmap(colors, position=None, bit=False, named=True)[source]

Make a color map compatible with matplotlib plotting functions.

Parameters:

colors : list

List of matplotlib named colors. Arrange your colors so that the first color is the lowest value for the colorbar and the last is the highest.

position : list

List of values from 0 to 1, controls the position of each color on the cmap. If None (default), an evenly spaced cmap is created.

Tip:

You can construct the positions sequence in data units and then normalize so that the forst value is 0 and the last value is 1.

named : bool

If set to False, colors are regarded as tuples of RGB values. The RGB values may either be in 8-bit [0 to 255], in which case bit must be set to True or arithmetic [0 to 1] (default).

Returns:

LinearSegmentedColormap

An instance of the LinearSegmentedColormap cmap class.

nearest_values(array, value, threshold, retvalue=False)[source]

Get the indices (or elements) of an array with a threshold range around a central value.

If retvalue is true, the elements of the array are returned, otherwise a True or False array of the indices of these elements is returned.

Examples

>>> array = np.random.randint(-10, 10, size=10)
>>> print(array)
[ 3 -4  9  6  8 -1 -4 -7 -6  7]
>>>
>>> idx = nearest_values(array, 5, 2)
>>> print(idx)
>>> print(nearest_values(array, 5, 2, retvalue=True))
>>> print array[idx]
[ True False False  True False False False False False  True]
[3 6 7]
[3 6 7]
resample(data, extent, shape=None, method='linear', draft=False, corners=None, origin='nw', verbose=False)[source]

Resample or interpolate an array on to a grid with new extent and or new shape.

Parameters:

data : 3-tuple or ndarray

Either a tuple of 3x2d ndarray s (X,Y,Z) or a single 2d ndarray Z. If a draft=True and a single Z array is passed, corners must be supplied.

extent : tuple or list

Extent of the output grid to which the array is interpolated.

shape : tuple

The shape of the output grid, defaults to the shape of the input array. If no shape is passed, output grid is the same shape as input array.

method : str

Method of interpolation. One of

  • nearest - return the value at the data point closest to the point of interpolation. This is the faster of the three.
  • linear - tesselate the input point set to n-dimensional simplices, and interpolate linearly on each simplex.
  • cubic - return the value determined from a piecewise cubic, continuously differentiable (C1), and approximately curvature-minimizing polynomial surface.

draft : bool

If set to True, a very fast OpenCV algorithem is used to interpolate the array by reprojection the data corners onto arbitrary corners. See Stack Overflow post for explanation.

corners : 4-tuple

Points to which the corners of Z will be tranformed to. After transformation, the TL, TR, BR, BL corners of the Z array will be transformed to the coordinates in:

corners=(top-left, top-right, bottom-right, bottom-left)

where each point is a tuple of (lon, lat). Optionally, corners can be a (src, dst) tuple, where src, dst are each a tuple of n points. Each point in src is transformed to the respective point in extent coordinates in dst.

origin : str

Corresponds to Z[0, 0] of the array or grid, either 'nw' (default), or 'sw'.

verbose : bool

If set to True, some information about the transformation is provided.

Returns:

3x2d ndarray s or 1x2d ndarray

If data is a tuple of 3x2d arrays (X,Y,Z) and draft is False, xi, yi, zi are returned. If draft is True, only zi is returned.

simple_lonlat2xy(lon, lat, lon0=0, lat0=0, az=0, m_per_lat=111319.5, m_per_lon=None)[source]

Project geographical lat, lon to cartesian x, y coordinates.

This is the inverse function of xy2latlon() function.

Parameters:

lon : float or sequence

lon coordianates.

lat : float or sequence

lat coordianates.

origin : 2-tuple or list

lat, lon coordinates of the bottom-right corner of the x, y grid.

az : float

Rotation of the grid aroud the vertical (z-axis). See the SW4 User Guide for more information.

m_per_lat : float

How many m to a degree latitude. (default: 111319.5 m)

m_per_lon : float

How many m to a degree longitude. If None, m_per_lat is used).

Returns:

2x ndarray

Two arrays with x and y projected points.

simple_xy2lonlat(x, y, lon0=0, lat0=0, az=0, m_per_lat=111319.5, m_per_lon=None)[source]

Project cartesian x, y coordinates to geographical lat, lon.

This transformation is based on the default projection used by SW4. See section 3.1.1 of the SW4 User Guide for more details.

     X
   ⋰
 ⋰
o------->Y
|
|
V
Z

If the azimuth of the SW4 grid is 0 this translates to:

  • X == Northing
  • Y == Easting
  • Z == Vertical (inverted!)
Parameters:

x : float or sequence

x coordianates.

y : float or sequence

y coordianates.

origin : 2-tuple or list

lat, lon coordinates of the bottom-right corner of the x, y grid.

az : float

Rotation of the grid aroud the vertical (z-axis). See the SW4 User Guide for more information.

m_per_lat : float

How many m to a degree latitude. (default: 111319.5 m)

m_per_lon : float

How many m to a degree longitude. If None, m_per_lat is used).

Returns:

2x ndarray

Two arrays with lon and lat projected points.

trim_cmap(cmap, cmin, cmax, n=256)[source]

Trim a cmap to cmin and cmax limits in the range 0 to 1. Use Normalize with vmin, vmax of the plot or data to get cmin and cmax

Examples

>>> norm = Normalize(-5, 10)
>>> norm(-2)
0.20000000000000001
>>> norm(6)
0.73333333333333328
xy2pixel_coordinates(x, y, extent, shape, origin='nw')[source]

Get the pixel coordinates on a grid.

Parameters:

x : float or sequence

x coordianates (might also be longitudes).

y : float or sequence

y coordianates (might also be latitudes).

extent : tuple or list

Extent of the output grid to which the array is interpolated.

shape : tuple

The shape of the output grid, defaults to the shape of the input array. If no shape is passed, output grid is the same shape as input array.

origin : str

Corresponds to Z[0, 0] of the array or grid, either 'nw' (default), or 'sw'.

Returns:

2x list

  • one list of longitudes (or x) and
  • another list of latitudes (or y).