scitools.BoxGrid

Class for uniform and non-uniform grid on an interval, rectangle, or box.

class scitools.BoxGrid.BoxGrid(coor, dirnames=('x', 'y', 'z'))[source]

Bases: scitools.BoxGrid.UniformBoxGrid

Extension of class UniformBoxGrid to non-uniform box grids. The coordinate vectors (in each space direction) can have arbitrarily spaced coordinate values.

The coor argument must be a list of nsd (number of space dimension) components, each component contains the grid coordinates in that space direction (stored as an array).

Methods

compatible(data_array[, name_of_data_array]) Check that data_array is a NumPy array with dimensions
dirindex2name(i) Inverse of name2dirindex.
gridline_slice(start_coor[, direction, end_coor]) Compute start and end indices of a line through the grid, and return a tuple that can be used as slice for the grid points along the line.
gridplane_slice(value[, constant_coor]) Compute a slice for a plane through the grid, defined by coor[constant_coor]=value.
init_fromstring(s)
interpolate(v0, v1, x0, x1, x)
interpolator(point_values) Given a self.nsd dimension array point_values with values at each grid point, this method returns a function for interpolating the scalar field defined by point_values at an arbitrary point.
iter([domain_part, vectorized_version]) Return iterator over grid points.
locate_cell(point)
name2dirindex(name) Return direction index corresponding to direction name.
ncells(i) Return no of cells in direction i.
ok()
string2griddata(s) Turn a text specification of a grid into a dictionary with the grid data.
vectorized_eval(f) Evaluate a function f (of the space directions) over a grid.
__class__

alias of type

__delattr__

x.__delattr__(‘name’) <==> del x.name

__dict__ = dict_proxy({'locate_cell': <function locate_cell at 0x3fa1848>, '__repr__': <function __repr__ at 0x3fa17d0>, '__module__': 'scitools.BoxGrid', '__init__': <function __init__ at 0x3fa1758>, '__doc__': '\n Extension of class UniformBoxGrid to non-uniform box grids.\n The coordinate vectors (in each space direction) can have\n arbitrarily spaced coordinate values.\n\n The coor argument must be a list of nsd (number of\n space dimension) components, each component contains the\n grid coordinates in that space direction (stored as an array).\n '})
__format__()

default object formatter

__getattribute__

x.__getattribute__(‘name’) <==> x.name

__getitem__(i)

Return access to coordinate array in direction no i, or direction name i, or return the coordinate of a point if i is an nsd-tuple.

>>> g = UniformBoxGrid(x=(0,1), y=(-1,1), nx=2, ny=4)  # xy grid
>>> g[0][0] == g.min[0]   # min coor in direction 0
True
>>> g['x'][0] == g.min[0]   # min coor in direction 'x'
True
>>> g[0,4]
(0.0, 1.0)
>>> g = UniformBoxGrid(min=(0,-1), max=(1,1), division=(2,4), dirnames=('y', 'z'))
>>> g[1][0] == g.min[1]
True
>>> g['z'][0] == g.min[1]   # min coor in direction 'z'
True
__hash__() <==> hash(x)
__init__(coor, dirnames=('x', 'y', 'z'))[source]
__iter__()
__len__()

Total number of grid points.

__module__ = 'scitools.BoxGrid'
static __new__(S, ...) → a new object with type S, a subtype of T
__reduce__()

helper for pickle

__reduce_ex__()

helper for pickle

__repr__()[source]
__setattr__

x.__setattr__(‘name’, value) <==> x.name = value

__setitem__(i, value)
__sizeof__() → int

size of object in memory, in bytes

__str__()

Pretty print, using the syntax of init_fromstring.

static __subclasshook__()

Abstract classes can override this to customize issubclass().

This is invoked early on by abc.ABCMeta.__subclasscheck__(). It should return True, False or NotImplemented. If it returns NotImplemented, the normal algorithm is used. Otherwise, it overrides the normal algorithm (and the outcome is cached).

__weakref__

list of weak references to the object (if defined)

compatible(data_array, name_of_data_array='')

Check that data_array is a NumPy array with dimensions compatible with the grid.

dirindex2name(i)

Inverse of name2dirindex.

gridline_slice(start_coor, direction=0, end_coor=None)

Compute start and end indices of a line through the grid, and return a tuple that can be used as slice for the grid points along the line.

The line must be in x, y or z direction (direction=0,1 or 2). If end_coor=None, the line ends where the grid ends. start_coor holds the coordinates of the start of the line. If start_coor does not coincide with one of the grid points, the line is snapped onto the grid (i.e., the line coincides with a grid line).

Return: tuple with indices and slice describing the grid point indices that make up the line, plus a boolean “snapped” which is True if the original line did not coincide with any grid line, meaning that the returned line was snapped onto to the grid.

>>> g2 = UniformBoxGrid.init_fromstring('[-1,1]x[-1,2] [0:3]x[0:4]')
>>> print g2.coor
[array([-1.        , -0.33333333,  0.33333333,  1.        ]),
 array([-1.  , -0.25,  0.5 ,  1.25,  2.  ])]
>>> g2.gridline_slice((-1, 0.5), 0)
((slice(0, 4, 1), 2), False)
>>> g2.gridline_slice((-0.9, 0.4), 0)
((slice(0, 4, 1), 2), True)
>>> g2.gridline_slice((-0.2, -1), 1)
((1, slice(0, 5, 1)), True)
gridplane_slice(value, constant_coor=0)

Compute a slice for a plane through the grid, defined by coor[constant_coor]=value.

Return a tuple that can be used as slice, plus a boolean parameter “snapped” reflecting if the plane was snapped onto a grid plane (i.e., value did not correspond to an existing grid plane).

static init_fromstring(s)
interpolate(v0, v1, x0, x1, x)
interpolator(point_values)

Given a self.nsd dimension array point_values with values at each grid point, this method returns a function for interpolating the scalar field defined by point_values at an arbitrary point.

2D Example: given a filled array point_values[i,j], compute interpolator = grid.interpolator(point_values) v = interpolator(0.1243, 9.231) # interpolate point_values

>>> g=UniformBoxGrid(x=(0,2), nx=2, y=(-1,1), ny=2)
>>> g
UniformBoxGrid(x=(0,2), nx=2, y=(-1,1), ny=2)
>>> def f(x,y): return 2+2*x-y
>>> f=g.vectorized_eval(f)
>>> f
array([[ 3.,  2.,  1.],
       [ 5.,  4.,  3.],
       [ 7.,  6.,  5.]])
>>> i=g.interpolator(f)
>>> i(0.1,0.234)        # interpolate (not a grid point)
1.9660000000000002
>>> f(0.1,0.234)        # exact answer
1.9660000000000002
iter(domain_part='all', vectorized_version=True)

Return iterator over grid points. domain_part = ‘all’: all grid points domain_part = ‘interior’: interior grid points domain_part = ‘all_boundary’: all boundary points domain_part = ‘interior_boundary’: interior boundary points domain_part = ‘corners’: all corner points domain_part = ‘all_edges’: all points along edges in 3D grids domain_part = ‘interior_edges’: interior points along edges

vectorized_version is true if the iterator returns slice objects for the index slice in each direction. vectorized_version is false if the iterator visits each point at a time (scalar version).

locate_cell(point)[source]
name2dirindex(name)

Return direction index corresponding to direction name. In an xyz-grid, ‘x’ is 0, ‘y’ is 1, and ‘z’ is 2. In an yz-grid, ‘x’ is not defined, ‘y’ is 0, and ‘z’ is 1.

ncells(i)

Return no of cells in direction i.

ok()
static string2griddata(s)

Turn a text specification of a grid into a dictionary with the grid data. For example,

>>> s = "domain=[0,10] indices=[0:11]"
>>> data = BoxGrid.string2griddata(s)
>>> data
{'dirnames': ('x', 'y'), 'division': [10], 'max': [10], 'min': [0]}
>>> s = "domain=[0.2,0.5]x[0,2E+00] indices=[0:20]x[0:100]"
>>> data = BoxGrid.string2griddata(s)
>>> data
{'dirnames': ('x', 'y', 'z'),
 'division': [19, 99],
 'max': [0.5, 2],
 'min': [0.2, 0]}
>>> s = "[0,1]x[0,2]x[-1,1.5] [0:25]x[0:10]x[0:16]"
>>> data = BoxGrid.string2griddata(s)
>>> data
{'dirnames': ('x', 'y', 'z'),
 'division': [24, 9, 15],
 'max': [1.0, 2.0, 1.5],
 'min': [0.0, 0.0, -1.0]}

The data dictionary can be used as keyword arguments to the class UniformBoxGrid constructor.

vectorized_eval(f)

Evaluate a function f (of the space directions) over a grid. f is supposed to be vectorized.

>>> g = BoxGrid(x=(0,1), y=(0,1), nx=3, ny=3)
>>> # f(x,y) = sin(x)*exp(x-y):
>>> a = g.vectorized_eval(lambda x,y: sin(x)*exp(y-x))
>>> print a
[[ 0.          0.          0.          0.        ]
 [ 0.23444524  0.3271947   0.45663698  0.63728825]
 [ 0.31748164  0.44308133  0.6183698   0.86300458]
 [ 0.30955988  0.43202561  0.60294031  0.84147098]]
>>> # f(x,y) = 2: (requires special consideration)
>>> a = g.vectorized_eval(lambda x,y: zeros(g.shape)+2)
>>> print a
[[ 2.  2.  2.  2.]
 [ 2.  2.  2.  2.]
 [ 2.  2.  2.  2.]
 [ 2.  2.  2.  2.]]
class scitools.BoxGrid.UniformBoxGrid(min=(0, 0), max=(1, 1), division=(4, 4), dirnames=('x', 'y', 'z'))[source]

Bases: object

Simple uniform grid on an interval, rectangle, box, or hypercube.

Attributes Description
nsd no of spatial dimensions in the grid
min_coor array of minimum coordinates
max_coor array of maximum coordinates
division array of cell divisions in the
delta array of grid spacings
dirnames names of the space directions (‘x’, ‘y’, etc.)
shape (nx+1, ny+1, ...); dimension of array over grid
coor list of coordinates; self.coor[Y][j] is the the j-th coordinate in direction Y (=1) X, Y, Z are predefined constants 0, 1, 2
coorv expanded version of coor for vectorized expressions (in 2D, self.coorv[0] = self.coor[0][:,newaxis])
tolerance small geometric tolerance based on grid coordinates
npoints total number of grid points

Methods

compatible(data_array[, name_of_data_array]) Check that data_array is a NumPy array with dimensions
dirindex2name(i) Inverse of name2dirindex.
gridline_slice(start_coor[, direction, end_coor]) Compute start and end indices of a line through the grid, and return a tuple that can be used as slice for the grid points along the line.
gridplane_slice(value[, constant_coor]) Compute a slice for a plane through the grid, defined by coor[constant_coor]=value.
init_fromstring(s)
interpolate(v0, v1, x0, x1, x)
interpolator(point_values) Given a self.nsd dimension array point_values with values at each grid point, this method returns a function for interpolating the scalar field defined by point_values at an arbitrary point.
iter([domain_part, vectorized_version]) Return iterator over grid points.
locate_cell(point) Given a point (x, (x,y), (x,y,z)), locate the cell in which the point is located, and return 1) the (i,j,k) vertex index of the “lower-left” grid point in this cell, 2) the distances (dx, (dx,dy), or (dx,dy,dz)) from this point to the given point, 3) a boolean list if point matches the coordinates of any grid lines.
name2dirindex(name) Return direction index corresponding to direction name.
ncells(i) Return no of cells in direction i.
ok()
string2griddata(s) Turn a text specification of a grid into a dictionary with the grid data.
vectorized_eval(f) Evaluate a function f (of the space directions) over a grid.
__class__

alias of type

__delattr__

x.__delattr__(‘name’) <==> del x.name

__dict__ = dict_proxy({'__module__': 'scitools.BoxGrid', 'init_fromstring': <staticmethod object at 0x3f99980>, '__getitem__': <function __getitem__ at 0x3f98de8>, '__str__': <function __str__ at 0x3fa1230>, '_more_init': <function _more_init at 0x3f98cf8>, 'interpolate': <function interpolate at 0x3fa15f0>, 'name2dirindex': <function name2dirindex at 0x3f98f50>, '__iter__': <function __iter__ at 0x3fa1500>, 'interpolator': <function interpolator at 0x3fa12a8>, '__dict__': <attribute '__dict__' of 'UniformBoxGrid' objects>, '__weakref__': <attribute '__weakref__' of 'UniformBoxGrid' objects>, '__init__': <function __init__ at 0x3f98c80>, 'ncells': <function ncells at 0x3f98ed8>, 'string2griddata': <staticmethod object at 0x3f99948>, 'locate_cell': <function locate_cell at 0x3fa1578>, 'gridline_slice': <function gridline_slice at 0x3fa1668>, 'ok': <function ok at 0x3fa10c8>, '__setitem__': <function __setitem__ at 0x3f98e60>, 'iter': <function iter at 0x3fa1488>, 'compatible': <function compatible at 0x3fa1410>, 'gridplane_slice': <function gridplane_slice at 0x3fa16e0>, '__repr__': <function __repr__ at 0x3fa11b8>, 'dirindex2name': <function dirindex2name at 0x3fa1050>, 'vectorized_eval': <function vectorized_eval at 0x3fa1320>, '__doc__': "\n Simple uniform grid on an interval, rectangle, box, or hypercube.\n\n ============= ====================================================\n Attributes Description\n ============= ====================================================\n nsd no of spatial dimensions in the grid\n min_coor array of minimum coordinates\n max_coor array of maximum coordinates\n division array of cell divisions in the \n delta array of grid spacings\n dirnames names of the space directions ('x', 'y', etc.)\n shape (nx+1, ny+1, ...); dimension of array over grid\n coor list of coordinates; self.coor[Y][j] is the\n the j-th coordinate in direction Y (=1)\n X, Y, Z are predefined constants 0, 1, 2\n coorv expanded version of coor for vectorized expressions\n (in 2D, self.coorv[0] = self.coor[0][:,newaxis])\n tolerance small geometric tolerance based on grid coordinates\n npoints total number of grid points\n ============= ====================================================\n\n ", '__len__': <function __len__ at 0x3fa1140>})
__format__()

default object formatter

__getattribute__

x.__getattribute__(‘name’) <==> x.name

__getitem__(i)[source]

Return access to coordinate array in direction no i, or direction name i, or return the coordinate of a point if i is an nsd-tuple.

>>> g = UniformBoxGrid(x=(0,1), y=(-1,1), nx=2, ny=4)  # xy grid
>>> g[0][0] == g.min[0]   # min coor in direction 0
True
>>> g['x'][0] == g.min[0]   # min coor in direction 'x'
True
>>> g[0,4]
(0.0, 1.0)
>>> g = UniformBoxGrid(min=(0,-1), max=(1,1), division=(2,4), dirnames=('y', 'z'))
>>> g[1][0] == g.min[1]
True
>>> g['z'][0] == g.min[1]   # min coor in direction 'z'
True
__hash__() <==> hash(x)
__init__(min=(0, 0), max=(1, 1), division=(4, 4), dirnames=('x', 'y', 'z'))[source]

Initialize a BoxGrid by giving domain range (minimum and maximum coordinates: min and max tuples/lists/arrays) and number of cells in each space direction (division tuple/list/array). The dirnames tuple/list holds the names of the coordinates in the various spatial directions.

>>> g = UniformBoxGrid(min=0, max=1, division=10)
>>> g = UniformBoxGrid(min=(0,-1), max=(1,1), division=(10,4))
>>> g = UniformBoxGrid(min=(0,0,-1), max=(2,1,1), division=(2,3,5))
__iter__()[source]
__len__()[source]

Total number of grid points.

__module__ = 'scitools.BoxGrid'
static __new__(S, ...) → a new object with type S, a subtype of T
__reduce__()

helper for pickle

__reduce_ex__()

helper for pickle

__repr__()[source]
__setattr__

x.__setattr__(‘name’, value) <==> x.name = value

__setitem__(i, value)[source]
__sizeof__() → int

size of object in memory, in bytes

__str__()[source]

Pretty print, using the syntax of init_fromstring.

static __subclasshook__()

Abstract classes can override this to customize issubclass().

This is invoked early on by abc.ABCMeta.__subclasscheck__(). It should return True, False or NotImplemented. If it returns NotImplemented, the normal algorithm is used. Otherwise, it overrides the normal algorithm (and the outcome is cached).

__weakref__

list of weak references to the object (if defined)

compatible(data_array, name_of_data_array='')[source]

Check that data_array is a NumPy array with dimensions compatible with the grid.

dirindex2name(i)[source]

Inverse of name2dirindex.

gridline_slice(start_coor, direction=0, end_coor=None)[source]

Compute start and end indices of a line through the grid, and return a tuple that can be used as slice for the grid points along the line.

The line must be in x, y or z direction (direction=0,1 or 2). If end_coor=None, the line ends where the grid ends. start_coor holds the coordinates of the start of the line. If start_coor does not coincide with one of the grid points, the line is snapped onto the grid (i.e., the line coincides with a grid line).

Return: tuple with indices and slice describing the grid point indices that make up the line, plus a boolean “snapped” which is True if the original line did not coincide with any grid line, meaning that the returned line was snapped onto to the grid.

>>> g2 = UniformBoxGrid.init_fromstring('[-1,1]x[-1,2] [0:3]x[0:4]')
>>> print g2.coor
[array([-1.        , -0.33333333,  0.33333333,  1.        ]),
 array([-1.  , -0.25,  0.5 ,  1.25,  2.  ])]
>>> g2.gridline_slice((-1, 0.5), 0)
((slice(0, 4, 1), 2), False)
>>> g2.gridline_slice((-0.9, 0.4), 0)
((slice(0, 4, 1), 2), True)
>>> g2.gridline_slice((-0.2, -1), 1)
((1, slice(0, 5, 1)), True)
gridplane_slice(value, constant_coor=0)[source]

Compute a slice for a plane through the grid, defined by coor[constant_coor]=value.

Return a tuple that can be used as slice, plus a boolean parameter “snapped” reflecting if the plane was snapped onto a grid plane (i.e., value did not correspond to an existing grid plane).

static init_fromstring(s)[source]
interpolate(v0, v1, x0, x1, x)[source]
interpolator(point_values)[source]

Given a self.nsd dimension array point_values with values at each grid point, this method returns a function for interpolating the scalar field defined by point_values at an arbitrary point.

2D Example: given a filled array point_values[i,j], compute interpolator = grid.interpolator(point_values) v = interpolator(0.1243, 9.231) # interpolate point_values

>>> g=UniformBoxGrid(x=(0,2), nx=2, y=(-1,1), ny=2)
>>> g
UniformBoxGrid(x=(0,2), nx=2, y=(-1,1), ny=2)
>>> def f(x,y): return 2+2*x-y
>>> f=g.vectorized_eval(f)
>>> f
array([[ 3.,  2.,  1.],
       [ 5.,  4.,  3.],
       [ 7.,  6.,  5.]])
>>> i=g.interpolator(f)
>>> i(0.1,0.234)        # interpolate (not a grid point)
1.9660000000000002
>>> f(0.1,0.234)        # exact answer
1.9660000000000002
iter(domain_part='all', vectorized_version=True)[source]

Return iterator over grid points. domain_part = ‘all’: all grid points domain_part = ‘interior’: interior grid points domain_part = ‘all_boundary’: all boundary points domain_part = ‘interior_boundary’: interior boundary points domain_part = ‘corners’: all corner points domain_part = ‘all_edges’: all points along edges in 3D grids domain_part = ‘interior_edges’: interior points along edges

vectorized_version is true if the iterator returns slice objects for the index slice in each direction. vectorized_version is false if the iterator visits each point at a time (scalar version).

locate_cell(point)[source]

Given a point (x, (x,y), (x,y,z)), locate the cell in which the point is located, and return 1) the (i,j,k) vertex index of the “lower-left” grid point in this cell, 2) the distances (dx, (dx,dy), or (dx,dy,dz)) from this point to the given point, 3) a boolean list if point matches the coordinates of any grid lines. If a point matches the last grid point in a direction, the cell index is set to the max index such that the (i,j,k) index can be used directly for look up in an array of values. The corresponding element in the distance array is then set 0. 4) the indices of the nearest grid point.

The method only works for uniform grid spacing. Used for interpolation.

>>> g1 = UniformBoxGrid(min=0, max=1, division=4)
>>> cell_index, distance, match, nearest = g1.locate_cell(0.7)
>>> print cell_index
[2]
>>> print distance
[ 0.2]
>>> print match
[False]
>>> print nearest
[3]
>>>
>>> g1.locate_cell(0.5)
([2], array([ 0.]), [True], [2])
>>>
>>> g2 = UniformBoxGrid.init_fromstring('[-1,1]x[-1,2] [0:3]x[0:4]')
>>> print g2.coor
[array([-1.        , -0.33333333,  0.33333333,  1.        ]), array([-1.  , -0.25,  0.5 ,  1.25,  2.  ])]
>>> g2.locate_cell((0.2,0.2))
([1, 1], array([ 0.53333333,  0.45      ]), [False, False], [2, 2])
>>> g2.locate_cell((1,2))
([3, 4], array([ 0.,  0.]), [True, True], [3, 4])
>>>
>>>
>>>
name2dirindex(name)[source]

Return direction index corresponding to direction name. In an xyz-grid, ‘x’ is 0, ‘y’ is 1, and ‘z’ is 2. In an yz-grid, ‘x’ is not defined, ‘y’ is 0, and ‘z’ is 1.

ncells(i)[source]

Return no of cells in direction i.

ok()[source]
static string2griddata(s)[source]

Turn a text specification of a grid into a dictionary with the grid data. For example,

>>> s = "domain=[0,10] indices=[0:11]"
>>> data = BoxGrid.string2griddata(s)
>>> data
{'dirnames': ('x', 'y'), 'division': [10], 'max': [10], 'min': [0]}
>>> s = "domain=[0.2,0.5]x[0,2E+00] indices=[0:20]x[0:100]"
>>> data = BoxGrid.string2griddata(s)
>>> data
{'dirnames': ('x', 'y', 'z'),
 'division': [19, 99],
 'max': [0.5, 2],
 'min': [0.2, 0]}
>>> s = "[0,1]x[0,2]x[-1,1.5] [0:25]x[0:10]x[0:16]"
>>> data = BoxGrid.string2griddata(s)
>>> data
{'dirnames': ('x', 'y', 'z'),
 'division': [24, 9, 15],
 'max': [1.0, 2.0, 1.5],
 'min': [0.0, 0.0, -1.0]}

The data dictionary can be used as keyword arguments to the class UniformBoxGrid constructor.

vectorized_eval(f)[source]

Evaluate a function f (of the space directions) over a grid. f is supposed to be vectorized.

>>> g = BoxGrid(x=(0,1), y=(0,1), nx=3, ny=3)
>>> # f(x,y) = sin(x)*exp(x-y):
>>> a = g.vectorized_eval(lambda x,y: sin(x)*exp(y-x))
>>> print a
[[ 0.          0.          0.          0.        ]
 [ 0.23444524  0.3271947   0.45663698  0.63728825]
 [ 0.31748164  0.44308133  0.6183698   0.86300458]
 [ 0.30955988  0.43202561  0.60294031  0.84147098]]
>>> # f(x,y) = 2: (requires special consideration)
>>> a = g.vectorized_eval(lambda x,y: zeros(g.shape)+2)
>>> print a
[[ 2.  2.  2.  2.]
 [ 2.  2.  2.  2.]
 [ 2.  2.  2.  2.]
 [ 2.  2.  2.  2.]]

This Page