spaceweight package

Submodules

spaceweight.plot_util module

spaceweight.plot_util.plot_2d_matrix(matrix, title='', figname=None)[source]

plot 2D matrix with color bar :param matrix: :param title: :param figname: :return:

spaceweight.plot_util.plot_circular_sector(csectors, title='Circular Sector')[source]

plot circular sectors in polar axis

Parameters:
  • csectors –
  • title –
Returns:

spaceweight.plot_util.plot_points_in_polar(rads, azis, mode='global', title='Points distribution')[source]

Plot the points in polar axis if given radius and azimuths

Parameters:
  • rads –
  • azis –
  • mode –
  • title –
Returns:

spaceweight.plot_util.plot_rings_in_polar(ring_bins, ring_edges, title='')[source]

Plot rings in polar axis given ring bins and ring edges

Parameters:
  • ring_bins –
  • ring_edges –
  • title –
Returns:

spaceweight.plot_util.plot_two_histograms(array1, array2, bin_edges=None, tag1='array1', tag2='array2')[source]

spaceweight.sphereazimuth module

Class that contains several azimuth weighting strategy on

surface of a sphere

Azimuth: 1) Relative Azimuth Weighting
  1. Bin Azimuth Weighting(from CMT3D, by Qinya Liu)
class spaceweight.sphereazimuth.SphereAziBin(points, bin_order=0.5, nbins=12, center=None, sort_by_tag=False, remove_duplicate=False, normalize_mode='average')[source]

Bases: spaceweight.sphereweightbase.SphereWeightBase

Sort Azimuth into certain number of bins and determine weight. Used in original version of CMT3D(Qinya Liu).

calculate_weight()[source]
class spaceweight.sphereazimuth.SphereAziRel(points, center=None, sort_by_tag=False, remove_duplicate=False, normalize_mode='average')[source]

Bases: spaceweight.sphereweightbase.SphereWeightBase

calculate_weight(ref_azimuth)[source]
plot_exp_matrix(figname=None)[source]
scan(start=0.5, end=10.0, gap=0.5, plot=False, figname=None)[source]

Scan among the range of ref_dists and return the condition number The defination of condition number is the max weight over min weight.

Parameters:
  • start – the start of ref_distance
  • end – the end of ref_distance
  • gap – the delta value
  • plot – plot flag
  • figname – save the figure to figname
Returns:

a list of ref_azimuth and condition numbers

smart_scan(max_ratio=0.5, start=0.5, gap=0.5, drop_ratio=0.9, plot=False, figname=None)[source]

Searching for the ref_azimuth by condition number which satisfy our condition. As the ref_distance increase from small values(near 0), we know that the condition number will first increase, reach its maxium and then decrease. The final ref_azimuth will satisfy:

optimal_cond_number = max_cond_number * max_ratio
The drop ratio determines the searching end point, which is:
end_cond_number = max_cond_number * drop_ratio
Parameters:
  • max_ratio – determine the optimal ref_azimuth(return value)
  • start – search start point
  • gap – delta
  • drop_ratio – determin the search end point
  • plot – plot flag
  • figname – figure name
Returns:

the optimal ref_azimuth and correspoinding condition number

spaceweight.spherevoronoi module

Spherical Voronoi Code

New in version 0.17.0.

class spaceweight.spherevoronoi.SphericalVoronoi(points, radius=None, center=None)[source]

Voronoi diagrams on the surface of a sphere.

New in version 0.17.0.

points : ndarray of floats, shape (npoints, 3)
Coordinates of points to construct a spherical Voronoi diagram from
radius : float, optional
Radius of the sphere (Default: 1)
center : ndarray of floats, shape (3,)
Center of sphere (Default: origin)
points : double array of shape (npoints, 3)
the points in 3D to generate the Voronoi diagram from
radius : double
radius of the sphere Default: None (forces estimation, which is less precise)
center : double array of shape (3,)
center of the sphere Default: None (assumes sphere is centered at origin)
vertices : double array of shape (nvertices, 3)
Voronoi vertices corresponding to points
regions : list of list of integers of shape (npoints, _ )
the n-th entry is a list consisting of the indices of the vertices belonging to the n-th point in points

The spherical Voronoi diagram algorithm proceeds as follows. The Convex Hull of the input points (generators) is calculated, and is equivalent to their Delaunay triangulation on the surface of the sphere [Caroli]. A 3D Delaunay tetrahedralization is obtained by including the origin of the coordinate system as the fourth vertex of each simplex of the Convex Hull. The circumcenters of all tetrahedra in the system are calculated and projected to the surface of the sphere, producing the Voronoi vertices. The Delaunay tetrahedralization neighbour information is then used to order the Voronoi region vertices around each generator. The latter approach is substantially less sensitive to floating point issues than angle-based methods of Voronoi region vertex sorting.

The surface area of spherical polygons is calculated by decomposing them into triangles and using L’Huilier’s Theorem to calculate the spherical excess of each triangle [Weisstein]. The sum of the spherical excesses is multiplied by the square of the sphere radius to obtain the surface area of the spherical polygon. For nearly-degenerate spherical polygons an area of approximately 0 is returned by default, rather than attempting the unstable calculation.

Empirical assessment of spherical Voronoi algorithm performance suggests quadratic time complexity (loglinear is optimal, but algorithms are more challenging to implement). The reconstitution of the surface area of the sphere, measured as the sum of the surface areas of all Voronoi regions, is closest to 100 % for larger (>> 10) numbers of generators.

[Caroli]Caroli et al. Robust and Efficient Delaunay triangulations of points on or close to a sphere. Research Report RR-7004, 2009.
[Weisstein]“L’Huilier’s Theorem.” From MathWorld – A Wolfram Web Resource. http://mathworld.wolfram.com/LHuiliersTheorem.html

Voronoi : Conventional Voronoi diagrams in N dimensions.

>>> from matplotlib import colors
>>> from mpl_toolkits.mplot3d.art3d import Poly3DCollection
>>> import matplotlib.pyplot as plt
>>> from scipy.spatial import SphericalVoronoi
>>> from mpl_toolkits.mplot3d import proj3d
>>> # set input data
>>> points = np.array([[0, 0, 1], [0, 0, -1], [1, 0, 0],
...                    [0, 1, 0], [0, -1, 0], [-1, 0, 0], ])
>>> center = np.array([0, 0, 0])
>>> radius = 1
>>> # calculate spherical Voronoi diagram
>>> sv = SphericalVoronoi(points, radius, center)
>>> # sort vertices (optional, helpful for plotting)
>>> sv.sort_vertices_of_regions()
>>> # generate plot
>>> fig = plt.figure()
>>> ax = fig.add_subplot(111, projection='3d')
>>> # plot the unit sphere for reference (optional)
>>> u = np.linspace(0, 2 * np.pi, 100)
>>> v = np.linspace(0, np.pi, 100)
>>> x = np.outer(np.cos(u), np.sin(v))
>>> y = np.outer(np.sin(u), np.sin(v))
>>> z = np.outer(np.ones(np.size(u)), np.cos(v))
>>> ax.plot_surface(x, y, z, color='y', alpha=0.1)
>>> # plot generator points
>>> ax.scatter(points[:, 0], points[:, 1], points[:, 2], c='b')
>>> # plot Voronoi vertices
>>> ax.scatter(sv.vertices[:, 0], sv.vertices[:, 1], sv.vertices[:, 2],
...                    c='g')
>>> # indicate Voronoi regions (as Euclidean polygons)
>>> for region in sv.regions:
...    random_color = colors.rgb2hex(np.random.rand(3))
...    polygon = Poly3DCollection([sv.vertices[region]], alpha=1.0)
...    polygon.set_color(random_color)
...    ax.add_collection3d(polygon)
>>> plt.show()
compute_surface_area()[source]

Returns a dictionary with the estimated surface areas of the Voronoi region polygons corresponding to each generator (original data point) index. An example dictionary entry: {generator_index : surface_area, ...}.

sort_vertices_of_regions()[source]

For each region in regions, it sorts the indices of the Voronoi vertices such that the resulting points are in a clockwise or counterclockwise order around the generator point.

This is done as follows: Recall that the n-th region in regions surrounds the n-th generator in points and that the k-th Voronoi vertex in vertices is the projected circumcenter of the tetrahedron obtained by the k-th triangle in _tri.simplices (and the origin). For each region n, we choose the first triangle (=Voronoi vertex) in _tri.simplices and a vertex of that triangle not equal to the center n. These determine a unique neighbor of that triangle, which is then chosen as the second triangle. The second triangle will have a unique vertex not equal to the current vertex or the center. This determines a unique neighbor of the second triangle, which is then chosen as the third triangle and so forth. We proceed through all the triangles (=Voronoi vertices) belonging to the generator in points and obtain a sorted version of the vertices of its surrounding region.

spaceweight.sphereweightbase module

Class that contains sphere weighting.

copyright:Wenjie Lei (lei@princeton.edu), 2016
license:GNU Lesser General Public License, version 3 (LGPLv3) (http://www.gnu.org/licenses/lgpl-3.0.en.html)
class spaceweight.sphereweightbase.SphereDistRel(points, center=None, sort_by_tag=False, remove_duplicate=False, normalize_mode='average')[source]

Bases: spaceweight.sphereweightbase.SphereWeightBase

Class that using the distances between points to calculate the weight. The basic idea is if two points are close to each other, the contribution to weight will be high(weight will be small).

calculate_weight(ref_distance)[source]

Calculate the weight based upon a given reference distance

Parameters:ref_distance –
Returns:
plot_exp_matrix(figname=None)[source]
scan(start=1.0, end=50.0, gap=1.0, plot=False, figname=None)[source]

Scan among the range of ref_dists and return the condition number The defination of condition number is the max weight over min weight.

Parameters:
  • start – the start of ref_distance
  • end – the end of ref_distance
  • gap – the delta value
  • plot – plot flag
  • figname – save the figure to figname
Returns:

a list of ref_distance and condition numbers

smart_scan(max_ratio=0.5, start=1.0, gap=0.5, drop_ratio=0.95, plot=False, figname=None)[source]

Searching for the ref_distance by condition number which satisfy our condition. As the ref_distance increase from small values(near 0), we know that the condition number will first increase, reach its maxium and then decrease. The final ref_distance will satisfy:

optimal_cond_number = max_cond_number * max_ratio
The drop ratio determines the searching end point, which is:
end_cond_number = max_cond_number * drop_ratio
Parameters:
  • max_ratio – determine the optimal ref_distance(return value)
  • start – search start point
  • gap – delta
  • drop_ratio – determin the search end point
  • plot – plot flag
  • figname – figure name
Returns:

the optimal ref_distance and correspoinding condition number

class spaceweight.sphereweightbase.SphereVoronoi(points, voronoi_order=1.0, center=None, sort_by_tag=False, remove_duplicate=True, normalize_mode='average')[source]

Bases: spaceweight.sphereweightbase.SphereWeightBase

calculate_weight()[source]
plot_sphere()[source]
class spaceweight.sphereweightbase.SphereWeightBase(points, center=None, sort_by_tag=False, remove_duplicate=False, normalize_mode='average')[source]

Bases: spaceweight.weightbase.WeightBase

The superclass for sphere weight. It handles 2D sphere problem, which means the points should be on the surface of a globe

plot_global_map(figname=None, lon0=None)[source]

Plot global map of points and centers

plot_station_weight_distribution(nbins=12, figname=None)[source]

Plot distribution of station and weight in azimuth bins

spaceweight.util module

Utils

spaceweight.util.get_bin_number(data, start, end, nbins)[source]

Calculate the bin number of given start, end and number of bins :param azimuth: test test test :return:

spaceweight.util.scale_matrix_by_exp(matrix, ref_value=1.0, order=2.0)[source]
Rescale the matrix value into exp value:
new_matrix[i][j] = exp(-(matrix[i][j] / ref_value) ** value)
Parameters:
  • matrix –
  • ref_value –
  • order –
Returns:

spaceweight.util.search_for_ratio(array, threshold)[source]

Point by point search yarray[i] ~= threshold

Parameters:
  • array –
  • threshold –
Returns:

the index of array element, and the value

spaceweight.util.sort_array_into_bins(array, start, end, nbins)[source]

spaceweight.weightbase module

Superclass of weight

copyright:Wenjie Lei (lei@princeton.edu), 2016
license:GNU Lesser General Public License, version 3 (LGPLv3) (http://www.gnu.org/licenses/lgpl-3.0.en.html)
class spaceweight.weightbase.WeightBase(points, sort_by_tag=False, remove_duplicate=False)[source]

Bases: object

The superclass for weighting. All the weighting results is supposed to be kept in the point.weight.

condition_number

Condition number is defined as max weight over min weight

detect_duplicate_tags()[source]
normalize_weight(mode='average')[source]

Normalize the weights while keep the ratio of points weights the same. Options are:

  1. “average”: normalize the average of weights to 1
  2. “max”: normalize the max of weights to 1
  3. “sum”: normalize the sum of weights to 1
Returns:
npoints
plot_weight_histogram(figname=None)[source]
points_coordinates
points_dimension
points_tags
points_weights
write_weight(filename='weight.txt', order='tag')[source]

Module contents

copyright:Lion Krischer (krischer@geophysik.uni-muenchen.de), 2014
license:GNU General Public License, Version 3 (http://www.gnu.org/copyleft/gpl.html)
class spaceweight.Point(coordinate, tag, weight=0.0)[source]

Bases: object

General definication of a point

dimension
class spaceweight.SpherePoint(latitude, longitude, tag, weight=0.0)[source]

Bases: spaceweight.Point

Point on the sphere, coordinates on latitude and longitude

latitude
longitude