src.utils#

This module contains miscellaneous helper functions and classes

Functions

delaunay(grid, cell[, res_x, res_y, xmax, ...])

Generates an idealised Delaunay triangle

gen_art_terrain(shp[, seed, iters])

Generates an artificial terrain

get_closest_idx(val, arr)

get_lat_lon_segments(lat_verts, lon_verts, ...)

Populates an empty cell object given the vertices and underlying topography.

get_size(obj[, seen])

Recursively finds size of objects

isosceles(grid, cell[, xmax, ymax, res, tri])

Populates a cell instance with an idealised triangle

latlon2m(arr, fix_pt, latlon)

Wrapper function to compute the distance of a list of values from a given fixed point (in meters).

pick_cell(lat_ref, lon_ref, grid[, radius])

Deprecated since version 0.90.0.

rad2deg(val)

Radians to degrees converter

rescale(arr[, rng])

Rescales a list to the interval of [0,1]

sliding_window_view(arr, window_shape, steps)

Produce a view from a sliding, striding window over arr.

Classes

gen_triangle(vx, vy[, x_rng, y_rng])

Defines a triangle generator given the coordinates of its vertices

taper(cell, padding[, stencil_typ, ...])

Helper class to apply tapering via artificial diffusion

src.utils.pick_cell(lat_ref, lon_ref, grid, radius=1.0)#

Deprecated since version 0.90.0.

src.utils.rad2deg(val)#

Radians to degrees converter

Parameters#

valfloat

argument in units of radians

Returns#

float

argument in units of degrees

src.utils.isosceles(grid, cell, xmax=6.283185307179586, ymax=6.283185307179586, res=480, tri='mid')#

Populates a cell instance with an idealised triangle

Parameters#

gridsrc.var.grid

instance of the grid class

cellsrc.var.topo_cell

instance of the cell class

xmaxfloat, optional

first horizontal extent, by default 2.0*np.pi

ymaxfloat, optional

second horizontal extent, by default 2.0*np.pi

resint, optional

resolution of the triangle, by default 480

tristr, optional

mid generates an isosceles triangle, left generates a lower and right an upper triangle. By default ‘mid’

Returns#

int

always returns 0, as this function generates only one triangle at index 0.

src.utils.delaunay(grid, cell, res_x=480, res_y=480, xmax=6.283185307179586, ymax=6.283185307179586, tri='lower')#

Generates an idealised Delaunay triangle

Parameters#

gridsrc.var.grid

instance of the grid class

cellsrc.var.topo_cell

instance of the cell class

res_xint, optional

resolution of the first horizontal extent, by default 480

res_yint, optional

resolution of the second horizontal extent, by default 480

xmaxfloat, optional

first horizontal extent, by default 2.0*np.pi

ymaxfloat, optional

second horizontal extent, by default 2.0*np.pi

tristr, optional

lower generates a lower triangle, and upper an upper triangle. By default ‘lower’

Returns#

int

always returns 0, as this function generates only one triangle at index 0.

src.utils.gen_art_terrain(shp, seed=555, iters=1000)#

Generates an artificial terrain

Deprecated since version 0.90.0.

Note

superceded by src.runs.idealised_test and src.runs.idealised_test_2

class src.utils.gen_triangle(vx, vy, x_rng=None, y_rng=None)#

Defines a triangle generator given the coordinates of its vertices

__init__(vx, vy, x_rng=None, y_rng=None)#

Defines the triangle’s properties

Parameters#

vxlist

[x1, x2, x3], list of the first coordinate of the vertices

vylist

[y1, y2, y3], list of the second coordinate of the vertices

x_rnglist, optional

[x_min, x_max]: the full first horizontal extent of the domain encompassing the triangle, by default None

y_rnglist, optional

[y_min, y_max]: the full second horizontal extent of the domain encompassing the triangle, by default None

Note

x_rng and y_rng are required if the triangle does not span the full extent of the grid cell.

src.utils.rescale(arr, rng=None)#

Rescales a list to the interval of [0,1]

Parameters#

arrlist

data points to be rescaled

rnglist, optional

extent to be rescaled, by default None

Returns#

list

arr values rescaled to [0,1]

Note

This rescaling is required to work with the fast triangle generator function.

src.utils.get_size(obj, seen=None)#

Recursively finds size of objects

Note

Function taken from https://github.com/bosswissam/pysize. Useful in checking how much memory is required by the data objects generated by src.var.

src.utils.get_lat_lon_segments(lat_verts, lon_verts, cell, topo, rect=False, filtered=True, padding=0, topo_mask=None, mask=None, load_topo=False)#

Populates an empty cell object given the vertices and underlying topography.

Parameters#

lat_vertslist

vertices of the cell in the first horizontal direction

lon_vertslist

vertices of the cell in the second horizontal direction

cellsrc.var.topo_cell

instance of the cell object class

toposrc.var.topo

instance of the topography object class

rectbool, optional

do the vertices describe a quadrilateral grid cell? By default False

filteredbool, optional

removes topographic features smaller than 5km in scale, by default True

paddingint, optional

number of data points in the padded region, by default 0

topo_maskarray-like, optional

tapering mask, by default None

maskarray-like, optional

2D Boolean mask to select for data points inside the non-quadrilateral grid cell, by default None

load_topobool, optional

explicitly replaces the topography attribute in the cell cell.topo with the data given in topo, by default False

src.utils.get_closest_idx(val, arr)#
src.utils.latlon2m(arr, fix_pt, latlon)#

Wrapper function to compute the distance of a list of values from a given fixed point (in meters).

Parameters#

arrlist

list of values in degrees

fix_ptfloat

given fixed point, e.g. the origin, in degrees

latlonstr

lat if the distance are to be computed in the latitudinal direction, lon otherwise.

Returns#

float

distance in meters

src.utils.sliding_window_view(arr, window_shape, steps)#

Produce a view from a sliding, striding window over arr. The window is only placed in ‘valid’ positions - no overlapping over the boundary.

Parameters#

arrnumpy.ndarray, shape=(…,[x, (…), z])

The array to slide the window over.

window_shapeSequence[int]

The shape of the window to raster: [Wx, (…), Wz], determines the length of [x, (…), z]

stepsSequence[int]

The step size used when applying the window along the [x, (…), z] directions: [Sx, (…), Sz]

Returns#

view of arr, shape=([X, (…), Z], …, [Wx, (…), Wz]), where X = (x - Wx) // Sx + 1

Note#

This function is taken from: https://gist.github.com/meowklaski/4bda7c86c6168f3557657d5fb0b5395a

In general, given:

out = sliding_window_view(arr,
                            window_shape=[Wx, (...), Wz],
                            steps=[Sx, (...), Sz])
out[ix, (...), iz] = arr[..., ix*Sx:ix*Sx+Wx,  (...), iz*Sz:iz*Sz+Wz]

Example#

>>> import numpy as np
>>> x = np.arange(9).reshape(3,3)
>>> x
array([[0, 1, 2],
    [3, 4, 5],
    [6, 7, 8]])
>>> y = sliding_window_view(x, window_shape=(2, 2), steps=(1, 1))
>>> y
array([[[[0, 1],
        [3, 4]],
        [[1, 2],
        [4, 5]]],
    [[[3, 4],
        [6, 7]],
        [[4, 5],
        [7, 8]]]])
>>> np.shares_memory(x, y)
    True
# Performing a neural net style 2D conv (correlation)
# placing a 4x4 filter with stride-1
>>> data = np.random.rand(10, 3, 16, 16)  # (N, C, H, W)
>>> filters = np.random.rand(5, 3, 4, 4)  # (F, C, Hf, Wf)
>>> windowed_data = sliding_window_view(data,
...                                     window_shape=(4, 4),
...                                     steps=(1, 1))
>>> conv_out = np.tensordot(filters,
...                         windowed_data,
...                         axes=[[1,2,3], [3,4,5]])
# (F, H', W', N) -> (N, F, H', W')
>>> conv_out = conv_out.transpose([3,0,1,2])
class src.utils.taper(cell, padding, stencil_typ='OP', scale_fac=1.0, art_dt=0.5, art_it=800)#

Helper class to apply tapering via artificial diffusion

__init__(cell, padding, stencil_typ='OP', scale_fac=1.0, art_dt=0.5, art_it=800)#

Initialises an artificial diffusion scenario

Parameters#

cellsrc.var.topo_cell

instance of the cell object class

paddingint

number of data points in the padded region

stencil_typstr, optional

Laplacian stencil choice, by default ‘OP’ which is also the most stable

scale_facfloat, optional

scaling factor for the stencil, by default 1.0

art_dtfloat, optional

artificial diffusion time-step size, by default 0.5

art_itint, optional

number of iterations for the artificial discussion, by default 800

do_tapering()#

Get tapered mask via artificial diffusion