本文整理汇总了Python中utilities.verify函数的典型用法代码示例。如果您正苦于以下问题:Python verify函数的具体用法?Python verify怎么用?Python verify使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了verify函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: bboxstring2list
def bboxstring2list(bbox_string):
"""Convert bounding box string to list
Input
bbox_string: String of bounding box coordinates of the form 'W,S,E,N'
Output
bbox: List of floating point numbers with format [W, S, E, N]
"""
msg = ('Bounding box must be a string with coordinates following the '
'format 105.592,-7.809,110.159,-5.647\n'
'Instead I got %s of type %s.' % (str(bbox_string),
type(bbox_string)))
verify(isinstance(bbox_string, basestring), msg)
fields = bbox_string.split(',')
msg = ('Bounding box string must have 4 coordinates in the form '
'"W,S,E,N". I got bbox == "%s"' % bbox_string)
verify(len(fields) == 4, msg)
for x in fields:
try:
float(x)
except ValueError, e:
msg = ('Bounding box %s contained non-numeric entry %s, '
'original error was "%s".' % (bbox_string, x, e))
raise AssertionError(msg)
示例2: grid_to_points
def grid_to_points(A, x, y):
"""Convert grid data to point data
:param A: Array of pixel values
:type A: numpy.ndarray
:param x: Longitudes corresponding to columns in A (west->east)
:type x: numpy.ndarray
:param y: Latitudes corresponding to rows in A (south->north)
:type y: numpy.ndarray
Returns:
* P: Nx2 array of point coordinates
* V: N array of point values
"""
msg = ('Longitudes must be increasing (west to east). I got %s' % str(x))
verify(x[0] < x[1], msg)
msg = ('Latitudes must be increasing (south to north). I got %s' % str(y))
verify(y[0] < y[1], msg)
# Create Nx2 array of x, y points corresponding to each
# element in A.
points = axes_to_points(x, y)
# Create flat 1D row-major view of A cast as
# one column vector of length MxN where M, N = A.shape
#values = A.reshape((-1, 1))
values = A.reshape(-1)
# Return Nx3 array with rows: x, y, value
return points, values
示例3: convert_polygons_to_centroids
def convert_polygons_to_centroids(V):
"""Convert polygon vector data to point vector data
:param V: Vector layer with polygon data
:type V: Vector
:returns: Vector layer with point data and the same attributes as V
:rtype: Vector
"""
msg = 'Input data %s must be polygon vector data' % V
verify(V.is_polygon_data, msg)
geometry = V.get_geometry()
N = len(V)
# Calculate points for each polygon
centroids = []
for i in range(N):
c = calculate_polygon_centroid(geometry[i])
centroids.append(c)
# Create new point vector layer with same attributes and return
V = Vector(data=V.get_data(),
projection=V.get_projection(),
geometry=centroids,
name='%s_centroid_data' % V.get_name(),
keywords=V.get_keywords())
return V
示例4: interpolate
def interpolate(self, X, name=None):
"""Interpolate values of this raster layer to other layer
Input
X: Layer object defining target
name: Optional name of interpolated layer.
If name is None, the name of self is used.
Output
Y: Layer object with values of this raster layer interpolated to
geometry of input layer X
Note: If target geometry is polygon, data will be interpolated to
its centroids and the output is a point data set.
"""
if X.is_raster:
if self.get_geotransform() != X.get_geotransform():
# Need interpolation between grids
msg = 'Intergrid interpolation not yet implemented'
raise Exception(msg)
else:
# Rasters are aligned, no need to interpolate
return self
else:
# Interpolate this raster layer to geometry of X
msg = ('Name must be either a string or None. I got %s'
% (str(type(X)))[1:-1])
verify(name is None or isinstance(name, basestring), msg)
return interpolate_raster_vector(self, X, name)
示例5: bboxlist2string
def bboxlist2string(bbox, decimals=6):
"""Convert bounding box list to comma separated string
Input
bbox: List of coordinates of the form [W, S, E, N]
Output
bbox_string: Format 'W,S,E,N' - each will have 6 decimal points
"""
msg = 'Got string %s, but expected bounding box as a list' % str(bbox)
verify(not isinstance(bbox, basestring), msg)
try:
bbox = list(bbox)
except:
msg = 'Could not coerce bbox %s into a list' % str(bbox)
raise Exception(msg)
msg = ('Bounding box must have 4 coordinates [W, S, E, N]. '
'I got %s' % str(bbox))
verify(len(bbox) == 4, msg)
for x in bbox:
try:
float(x)
except ValueError, e:
msg = ('Bounding box %s contained non-numeric entry %s, '
'original error was "%s".' % (bbox, x, e))
raise AssertionError(msg)
示例6: convert_line_to_points
def convert_line_to_points(V, delta):
"""Convert line vector data to point vector data
Input
V: Vector layer with line data
delta: Incremental step to find the points
Output
Vector layer with point data and the same attributes as V
"""
msg = 'Input data %s must be line vector data' % V
verify(V.is_line_data, msg)
geometry = V.get_geometry()
data = V.get_data()
N = len(V)
# Calculate centroids for each polygon
points = []
new_data = []
for i in range(N):
c = points_along_line(geometry[i], delta)
# We need to create a data entry for each point.
new_data.extend([data[i] for thing in c])
points.extend(c)
# Create new point vector layer with same attributes and return
V = Vector(data=new_data,
projection=V.get_projection(),
geometry=points,
name='%s_point_data' % V.get_name(),
keywords=V.get_keywords())
return V
示例7: geotransform_to_axes
def geotransform_to_axes(G, nx, ny):
"""Convert geotransform to coordinate axes
:param G: GDAL geotransform (6-tuple).
(top left x, w-e pixel resolution, rotation,
top left y, rotation, n-s pixel resolution).
:type G: tuple
:param nx: Number of cells in the w-e direction
:type nx: int
:param ny: Number of cells in the n-s direction
:type nx: int
:returns: Two vectors (longitudes and latitudes) representing the grid
defined by the geotransform.
The values are offset by half a pixel size to correspond to
pixel registration.
I.e. If the grid origin (top left corner) is (105, 10) and the
resolution is 1 degrees in each direction, then the vectors will
take the form
longitudes = [100.5, 101.5, ..., 109.5]
latitudes = [0.5, 1.5, ..., 9.5]
"""
lon_ul = float(G[0]) # Longitude of upper left corner
lat_ul = float(G[3]) # Latitude of upper left corner
dx = float(G[1]) # Longitudinal resolution
dy = - float(G[5]) # Latitudinal resolution (always(?) negative)
verify(dx > 0)
verify(dy > 0)
# Coordinates of lower left corner
lon_ll = lon_ul
lat_ll = lat_ul - ny * dy
# Coordinates of upper right corner
lon_ur = lon_ul + nx * dx
# Define pixel centers along each directions
# This is to achieve pixel registration rather
# than gridline registration
dx2 = dx / 2
dy2 = dy / 2
# Define longitudes and latitudes for each axes
x = numpy.linspace(lon_ll + dx2,
lon_ur - dx2, nx)
y = numpy.linspace(lat_ll + dy2,
lat_ul - dy2, ny)
# Return
return x, y
示例8: axes_to_points
def axes_to_points(x, y):
"""Generate all combinations of grid point coordinates from x and y axes
:param x: x coordinates (array)
:type x: numpy.ndarray
:param y: y coordinates (array)
:type y: numpy.ndarray
:returns:
* P: Nx2 array consisting of coordinates for all
grid points defined by x and y axes. The x coordinate
will vary the fastest to match the way 2D numpy
arrays are laid out by default ('C' order). That way,
the x and y coordinates will match a corresponding
2D array A when flattened (A.flat[:] or A.reshape(-1))
Note:
Example
x = [1, 2, 3]
y = [10, 20]
P = [[1, 10],
[2, 10],
[3, 10],
[1, 20],
[2, 20],
[3, 20]]
"""
# Reverse y coordinates to have them start at bottom of array
y = numpy.flipud(y)
# Repeat x coordinates for each y (fastest varying)
# noinspection PyTypeChecker
X = numpy.kron(numpy.ones(len(y)), x)
# Repeat y coordinates for each x (slowest varying)
Y = numpy.kron(y, numpy.ones(len(x)))
# Check
N = len(X)
verify(len(Y) == N)
# Create Nx2 array of x and y coordinates
X = numpy.reshape(X, (N, 1))
Y = numpy.reshape(Y, (N, 1))
P = numpy.concatenate((X, Y), axis=1)
# Return
return P
示例9: get_geometry
def get_geometry(self):
"""Return longitudes and latitudes (the axes) for grid.
Return two vectors (longitudes and latitudes) corresponding to
grid. The values are offset by half a pixel size to correspond to
pixel registration.
I.e. If the grid origin (top left corner) is (105, 10) and the
resolution is 1 degrees in each direction, then the vectors will
take the form
longitudes = [100.5, 101.5, ..., 109.5]
latitudes = [0.5, 1.5, ..., 9.5]
"""
# Get parameters for axes
g = self.get_geotransform()
lon_ul = g[0] # Longitude of upper left corner
lat_ul = g[3] # Latitude of upper left corner
dx = g[1] # Longitudinal resolution
dy = - g[5] # Latitudinal resolution (always(?) negative)
nx = self.columns
ny = self.rows
verify(dx > 0)
verify(dy > 0)
# Coordinates of lower left corner
lon_ll = lon_ul
lat_ll = lat_ul - ny * dy
# Coordinates of upper right corner
lon_ur = lon_ul + nx * dx
# Define pixel centers along each directions
dy2 = dy / 2
dx2 = dx / 2
# Define longitudes and latitudes for each axes
x = numpy.linspace(lon_ll + dx2,
lon_ur - dx2, nx)
y = numpy.linspace(lat_ll + dy2,
lat_ul - dy2, ny)
# Return
return x, y
示例10: write_to_file
def write_to_file(self, filename):
"""Save raster data to file
Input
filename: filename with extension .tif
"""
# Check file format
basename, extension = os.path.splitext(filename)
msg = ('Invalid file type for file %s. Only extension '
'tif allowed.' % filename)
verify(extension in ['.tif', '.asc'], msg)
format = DRIVER_MAP[extension]
# Get raster data
A = self.get_data()
# Get Dimensions. Note numpy and Gdal swap order
N, M = A.shape
# Create empty file.
# FIXME (Ole): It appears that this is created as single
# precision even though Float64 is specified
# - see issue #17
driver = gdal.GetDriverByName(format)
fid = driver.Create(filename, M, N, 1, gdal.GDT_Float64)
if fid is None:
msg = ('Gdal could not create filename %s using '
'format %s' % (filename, format))
raise Exception(msg)
# Write metada
fid.SetProjection(str(self.projection))
fid.SetGeoTransform(self.geotransform)
# Write data
fid.GetRasterBand(1).WriteArray(A)
# Write keywords if any
write_keywords(self.keywords, basename + '.keywords')
示例11: convert_line_to_points
def convert_line_to_points(V, delta):
"""Convert line vector data to point vector data
:param V: Vector layer with line data
:type V: Vector
:param delta: Incremental step to find the points
:type delta: float
:returns: Vector layer with point data and the same attributes as V
:rtype: Vector
"""
msg = 'Input data %s must be line vector data' % V
verify(V.is_line_data, msg)
geometry = V.get_geometry()
data = V.get_data()
N = len(V)
# Calculate centroids for each polygon
points = []
new_data = []
for i in range(N):
c = points_along_line(geometry[i], delta)
# We need to create a data entry for each point.
# FIXME (Ole): What on earth is this?
# pylint: disable=W0621
new_data.extend([data[i] for _ in c])
# pylint: enable=W0621
points.extend(c)
# Create new point vector layer with same attributes and return
V = Vector(data=new_data,
projection=V.get_projection(),
geometry=points,
name='%s_point_data' % V.get_name(),
keywords=V.get_keywords())
return V
示例12: get_bins
def get_bins(self, N=10, quantiles=False):
"""Get N values between the min and the max occurred in this dataset.
Return sorted list of length N+1 where the first element is min and
the last is max. Intermediate values depend on the keyword quantiles:
If quantiles is True, they represent boundaries between quantiles.
If quantiles is False, they represent equidistant interval boundaries.
"""
min, max = self.get_extrema()
levels = []
if quantiles is False:
# Linear intervals
d = (max - min) / N
for i in range(N):
levels.append(min + i * d)
else:
# Quantiles
# FIXME (Ole): Not 100% sure about this algorithm,
# but it is close enough
A = self.get_data(nan=True).flat[:]
mask = numpy.logical_not(numpy.isnan(A)) # Omit NaN's
A = A.compress(mask)
A.sort()
verify(len(A) == A.shape[0])
d = float(len(A) + 0.5) / N
for i in range(N):
levels.append(A[int(i * d)])
levels.append(max)
return levels
示例13: get_data
def get_data(self, attribute=None, index=None):
"""Get vector attributes
Data is returned as a list where each entry is a dictionary of
attributes for one feature. Entries in get_geometry() and
get_data() are related as 1-to-1
If optional argument attribute is specified and a valid name,
then the list of values for that attribute is returned.
If optional argument index is specified on the that value will
be returned. Any value of index is ignored if attribute is None.
"""
if hasattr(self, 'data'):
if attribute is None:
return self.data
else:
msg = ('Specified attribute %s does not exist in '
'vector layer %s. Valid names are %s'
'' % (attribute, self, self.data[0].keys()))
verify(attribute in self.data[0], msg)
if index is None:
# Return all values for specified attribute
return [x[attribute] for x in self.data]
else:
# Return value for specified attribute and index
msg = ('Specified index must be either None or '
'an integer. I got %s' % index)
verify(type(index) == type(0), msg)
msg = ('Specified index must lie within the bounds '
'of vector layer %s which is [%i, %i]'
'' % (self, 0, len(self) - 1))
verify(0 <= index < len(self), msg)
return self.data[index][attribute]
else:
msg = 'Vector data instance does not have any attributes'
raise Exception(msg)
示例14: get_topN
def get_topN(self, attribute, N=10):
"""Get top N features
Input
attribute: The name of attribute where values are sought
N: How many
Output
layer: New vector layer with selected features
"""
# FIXME (Ole): Maybe generalise this to arbitrary expressions
# Input checks
msg = ('Specfied attribute must be a string. '
'I got %s' % (type(attribute)))
verify(isinstance(attribute, basestring), msg)
msg = 'Specified attribute was empty'
verify(attribute != '', msg)
msg = 'N must be a positive number. I got %i' % N
verify(N > 0, msg)
# Create list of values for specified attribute
values = self.get_data(attribute)
# Sort and select using Schwarzian transform
A = zip(values, self.data, self.geometry)
A.sort()
# Pick top N and unpack
_, data, geometry = zip(*A[-N:])
# Create new Vector instance and return
return Vector(data=data,
projection=self.get_projection(),
geometry=geometry)
示例15: get_topN
def get_topN(self, attribute, N=10):
"""Get top N features
:param attribute: The name of attribute where values are sought
:type attribute: str
:param N: How many
:type N: int
:returns: New vector layer with selected features
"""
# Input checks
msg = ('Specfied attribute must be a string. '
'I got %s' % (type(attribute)))
verify(isinstance(attribute, basestring), msg)
msg = 'Specified attribute was empty'
verify(attribute != '', msg)
msg = 'N must be a positive number. I got %i' % N
verify(N > 0, msg)
# Create list of values for specified attribute
values = self.get_data(attribute)
# Sort and select using Schwarzian transform
A = zip(values, self.data, self.geometry)
A.sort()
# Pick top N and unpack
data, geometry = zip(*A[-N:])[1:]
# Create new Vector instance and return
return Vector(data=data,
projection=self.get_projection(),
geometry=geometry,
keywords=self.get_keywords())