def test_NotImplemented_not_returned(self):
# See gh-5964 and gh-2091. Some of these functions are not operator
# related and were fixed for other reasons in the past.
binary_funcs = [
np.power, np.add, np.subtract, np.multiply, np.divide,
np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
np.logical_and, np.logical_or, np.logical_xor, np.maximum,
np.minimum, np.mod
]
# These functions still return NotImplemented. Will be fixed in
# future.
# bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]
a = np.array('1')
b = 1
for f in binary_funcs:
assert_raises(TypeError, f, a, b)
python类hypot()的实例源码
def _vlines(lines, ctrs=None, lengths=None, vecs=None, angle_lo=20, angle_hi=160, ransac_options=RANSAC_OPTIONS):
ctrs = ctrs if ctrs is not None else lines.mean(1)
vecs = vecs if vecs is not None else lines[:, 1, :] - lines[:, 0, :]
lengths = lengths if lengths is not None else np.hypot(vecs[:, 0], vecs[:, 1])
angles = np.degrees(np.arccos(vecs[:, 0] / lengths))
points = np.column_stack([ctrs[:, 0], angles])
point_indices, = np.nonzero((angles > angle_lo) & (angles < angle_hi))
points = points[point_indices]
if len(points) > 2:
model_ransac = linear_model.RANSACRegressor(**ransac_options)
model_ransac.fit(points[:, 0].reshape(-1, 1), points[:, 1].reshape(-1, 1))
inlier_mask = model_ransac.inlier_mask_
valid_lines = lines[point_indices[inlier_mask], :, :]
else:
valid_lines = []
return valid_lines
def _hlines(lines, ctrs=None, lengths=None, vecs=None, angle_lo=20, angle_hi=160, ransac_options=RANSAC_OPTIONS):
ctrs = ctrs if ctrs is not None else lines.mean(1)
vecs = vecs if vecs is not None else lines[:, 1, :] - lines[:, 0, :]
lengths = lengths if lengths is not None else np.hypot(vecs[:, 0], vecs[:, 1])
angles = np.degrees(np.arccos(vecs[:, 1] / lengths))
points = np.column_stack([ctrs[:, 1], angles])
point_indices, = np.nonzero((angles > angle_lo) & (angles < angle_hi))
points = points[point_indices]
if len(points) > 2:
model_ransac = linear_model.RANSACRegressor(**ransac_options)
model_ransac.fit(points[:, 0].reshape(-1, 1), points[:, 1].reshape(-1, 1))
inlier_mask = model_ransac.inlier_mask_
valid_lines = lines[point_indices[inlier_mask], :, :]
else:
valid_lines = []
return valid_lines
def get_ind_under_point(self, event):
"""
get the index of the vertex under point if within epsilon tolerance
:param event: qt event
:return: index of selected point
"""
# display coords
distances = numpy.hypot(event.xdata - self.curData[:, 0],
event.ydata - self.curData[:, 1])
indmin = distances.argmin()
if distances[indmin] >= self.epsilon:
ind = None
else:
ind = indmin
self.lastind = ind
return ind
def get_ind_under_point(self, event):
"""
get the index of the vertex under point if within epsilon tolerance
:param event: qt event
:return: index of selected point
"""
# display coords
distances = numpy.hypot(event.xdata - self.curData[:, 0],
event.ydata - self.curData[:, 1])
indmin = distances.argmin()
if distances[indmin] >= self.epsilon:
ind = None
else:
ind = indmin
self.lastind = ind
return ind
def calcPi(n):
""" Calculating Pi using Monte Carlo Integration.
Quickly estimates the first 2 decimals, but it is terribly inefficient for estimating other decimals.
Source: http://www.stealthcopter.com/blog/2009/09/python-calculating-pi-using-random-numbers/
"""
inside = 0.0
for i in range(n):
x = np.random.random()
y = np.random.random()
# Calculate the length of hypotenuse given the sides x and y
if np.hypot(x, y) <= 1:
inside += 1
return 4.0*inside/n
# Run the calcPi function without timing
def test_NotImplemented_not_returned(self):
# See gh-5964 and gh-2091. Some of these functions are not operator
# related and were fixed for other reasons in the past.
binary_funcs = [
np.power, np.add, np.subtract, np.multiply, np.divide,
np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
np.logical_and, np.logical_or, np.logical_xor, np.maximum,
np.minimum, np.mod
]
# These functions still return NotImplemented. Will be fixed in
# future.
# bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]
a = np.array('1')
b = 1
for f in binary_funcs:
assert_raises(TypeError, f, a, b)
def _filter(img, method, k):
if method == 'Edge gradient':
sy = cv2.Sobel(img, ddepth=cv2.CV_64F, dx=0, dy=1, ksize=k)
sx = cv2.Sobel(img, ddepth=cv2.CV_64F,dx=1, dy=0, ksize=k)
# sx = sobel(img, axis=0, mode='constant')
# sy = sobel(img, axis=1, mode='constant')
return np.hypot(sx, sy)
if method == 'Sobel-H':
return cv2.Sobel(img, ddepth=cv2.CV_64F,dx=0, dy=1, ksize=k)
#sobel(img, axis=0, mode='constant')
if method == 'Sobel-V':
return cv2.Sobel(img, ddepth=cv2.CV_64F,dx=1, dy=0, ksize=k)
#sobel(img, axis=1, mode='constant')
if method == 'Laplace':
return cv2.Laplacian(img, ddepth=cv2.CV_64F,ksize=5)
#laplace(img)
def _pixel_select(self, event):
x, y = event.xdata, event.ydata
# get index by assuming even spacing
# TODO use kdtree?
diff = np.hypot((self.x_pos - x), (self.y_pos - y))
y_ind, x_ind = np.unravel_index(np.argmin(diff), diff.shape)
# get the spectrum for this point
new_y_data = self.counts[y_ind, x_ind, :]
self.mask = np.zeros(self.x_pos.shape, dtype='bool')
self.mask[y_ind, x_ind] = True
self.mask_im.set_data(self._overlay_image)
self._pixel_txt.set_text(
'pixel: [{:d}, {:d}] ({:.3g}, {:.3g})'.format(
y_ind, x_ind,
self.x_pos[y_ind, x_ind],
self.y_pos[y_ind, x_ind]))
self.spec.set_ydata(new_y_data)
self.ax_spec.relim()
self.ax_spec.autoscale(True, axis='y')
self.fig.canvas.draw_idle()
def line_ball_collision_check(line, ball):
# checks if the ball is half the line length from the line middle
if distance_less_equal(line.middle, ball.pos, line.length / 2 + config.ball_radius):
# displacement vector from the first point to the ball
displacement_to_ball = ball.pos - line.line[0]
# displacement vector from the first point to the second point on the
# line
displacement_to_second_point = line.line[1] - line.line[0]
normalised_point_diff_vector = displacement_to_second_point / \
np.hypot(*(displacement_to_second_point))
# distance from the first point on the line to the perpendicular
# projection point from the ball
projected_distance = np.dot(normalised_point_diff_vector, displacement_to_ball)
# closest point on the line to the ball
closest_line_point = projected_distance * normalised_point_diff_vector
perpendicular_vector = np.array(
[-normalised_point_diff_vector[1], normalised_point_diff_vector[0]])
# checking if closest point on the line is actually on the line (which is not always the case when projecting)
# then checking if the distance from that point to the ball is less than the balls radius and finally
# checking if the ball is moving towards the line with the dot product
return -config.ball_radius / 3 <= projected_distance <= \
np.hypot(*(displacement_to_second_point)) + config.ball_radius / 3 and \
np.hypot(*(closest_line_point - ball.pos + line.line[0])) <= \
config.ball_radius and np.dot(
perpendicular_vector, ball.velocity) <= 0
test_ufunc.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def test_NotImplemented_not_returned(self):
# See gh-5964 and gh-2091. Some of these functions are not operator
# related and were fixed for other reasons in the past.
binary_funcs = [
np.power, np.add, np.subtract, np.multiply, np.divide,
np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
np.logical_and, np.logical_or, np.logical_xor, np.maximum,
np.minimum, np.mod
]
# These functions still return NotImplemented. Will be fixed in
# future.
# bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]
a = np.array('1')
b = 1
for f in binary_funcs:
assert_raises(TypeError, f, a, b)
def go_to_with_planner(self, x, y, t):
start = self.position()[:-1]
end = np.array([x, y])
points = self.planner.get_points(start=start, end=end, robot=self)
def add_t(points, t):
points = np.array(points)
lens = np.hypot(points[:, 0], points[:, 1])
tpm = t / np.add.reduce(lens)
npoints = np.zeros(shape=(points.shape[0], 3))
npoints[:, :-1] = points
npoints[:, -1] = tpm * lens
return npoints
npoints = add_t(points, t)
if not points:
logging.warning("no available path. start=%r, end=%r", start, end)
else:
self.follow(points, t)
def test_NotImplemented_not_returned(self):
# See gh-5964 and gh-2091. Some of these functions are not operator
# related and were fixed for other reasons in the past.
binary_funcs = [
np.power, np.add, np.subtract, np.multiply, np.divide,
np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
np.logical_and, np.logical_or, np.logical_xor, np.maximum,
np.minimum, np.mod
]
# These functions still return NotImplemented. Will be fixed in
# future.
# bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]
a = np.array('1')
b = 1
for f in binary_funcs:
assert_raises(TypeError, f, a, b)
def dist(apos, bpos):
"""
Angular separation between two points on a sphere.
http://en.wikipedia.org/wiki/Great-circle_distance
"""
(a_ra, a_dec), (b_ra, b_dec) = apos, bpos
lon1 = a_ra / 180 * pi
lat1 = a_dec / 180 * pi
lon2 = b_ra / 180 * pi
lat2 = b_dec / 180 * pi
sdlon = sin(lon2 - lon1)
cdlon = cos(lon2 - lon1)
slat1 = sin(lat1)
slat2 = sin(lat2)
clat1 = cos(lat1)
clat2 = cos(lat2)
num1 = clat2 * sdlon
num2 = clat1 * slat2 - slat1 * clat2 * cdlon
denominator = slat1 * slat2 + clat1 * clat2 * cdlon
return arctan2(hypot(num1, num2), denominator) * 180 / pi
def test_NotImplemented_not_returned(self):
# See gh-5964 and gh-2091. Some of these functions are not operator
# related and were fixed for other reasons in the past.
binary_funcs = [
np.power, np.add, np.subtract, np.multiply, np.divide,
np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
np.logical_and, np.logical_or, np.logical_xor, np.maximum,
np.minimum, np.mod
]
# These functions still return NotImplemented. Will be fixed in
# future.
# bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]
a = np.array('1')
b = 1
for f in binary_funcs:
assert_raises(TypeError, f, a, b)
def test_NotImplemented_not_returned(self):
# See gh-5964 and gh-2091. Some of these functions are not operator
# related and were fixed for other reasons in the past.
binary_funcs = [
np.power, np.add, np.subtract, np.multiply, np.divide,
np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
np.logical_and, np.logical_or, np.logical_xor, np.maximum,
np.minimum, np.mod
]
# These functions still return NotImplemented. Will be fixed in
# future.
# bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]
a = np.array('1')
b = 1
for f in binary_funcs:
assert_raises(TypeError, f, a, b)
def direction_map(dmap: DistanceMap):
r"""Computes normalized gradient of distance map. Not defined when length of
the gradient is zero.
.. math::
\hat{\mathbf{e}}_{S} = -\frac{\nabla S(\mathbf{x})}{\| \nabla S(\mathbf{x}) \|}
Args:
dmap (numpy.ndarray):
Distance map.
Returns:
DirectionMap: Direction map.
"""
u, v = np.gradient(dmap)
l = np.hypot(u, v)
# Avoids zero division
l[l == 0] = np.nan
# Flip order from (row, col) to (x, y)
return v / l, u / l
# Potentials
def collide(self, p1, p2):
np = self.np
dx = p1.x - p2.x
dy = p1.y - p2.y
elasticity = 1
dist = np.hypot(dx, dy)
if dist < p1.size + p2.size:
tangent = np.arctan2(dy, dx)
angle = 0.5 * np.pi + tangent
angle1 = 2*tangent - p1.angle
angle2 = 2*tangent - p2.angle
speed1 = p2.speed*elasticity
speed2 = p1.speed*elasticity
(p1.angle, p1.speed) = (angle1, speed1)
(p2.angle, p2.speed) = (angle2, speed2)
p1.x += np.sin(angle)
p1.y -= np.cos(angle)
p2.x -= np.sin(angle)
p2.y += np.cos(angle)
sphere_transforms_numpy.py 文件源码
项目:spherical_image_editing
作者: henryseg
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def angles_from_sphere(pts):
"""equirectangular projection, ie. map from sphere in R^3 to (0, 2*pi) x (-pi/2, pi/2)
Parameters
----------
pts : array_like (3,...)
pts[0,...], pts[1,...], and pts[2,...] are x,y, and z coordinates
Returns
-------
out : ndarray (2,...)
pts transformed from x,y,z to longitude,latitude
"""
pts = np.asarray(pts) #turn into an ndarray if necessary
x,y,z = pts[0], pts[1], pts[2]
out = np.empty((2,) + pts.shape[1:])
#longitude:
out[0] = np.arctan2(y,x)
out[0] %= 2*pi #wrap negative values around the circle to positive
#latitude:
r = np.hypot(x,y)
out[1] = np.arctan2(z,r)
return out
def test_NotImplemented_not_returned(self):
# See gh-5964 and gh-2091. Some of these functions are not operator
# related and were fixed for other reasons in the past.
binary_funcs = [
np.power, np.add, np.subtract, np.multiply, np.divide,
np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
np.logical_and, np.logical_or, np.logical_xor, np.maximum,
np.minimum, np.mod
]
# These functions still return NotImplemented. Will be fixed in
# future.
# bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]
a = np.array('1')
b = 1
for f in binary_funcs:
assert_raises(TypeError, f, a, b)
def get_dH2(lab1, lab2):
"""squared hue difference term occurring in deltaE_cmc and deltaE_ciede94
Despite its name, "dH" is not a simple difference of hue values. We avoid
working directly with the hue value, since differencing angles is
troublesome. The hue term is usually written as:
c1 = sqrt(a1**2 + b1**2)
c2 = sqrt(a2**2 + b2**2)
term = (a1-a2)**2 + (b1-b2)**2 - (c1-c2)**2
dH = sqrt(term)
However, this has poor roundoff properties when a or b is dominant.
Instead, ab is a vector with elements a and b. The same dH term can be
re-written as:
|ab1-ab2|**2 - (|ab1| - |ab2|)**2
and then simplified to:
2*|ab1|*|ab2| - 2*dot(ab1, ab2)
"""
lab1 = np.asarray(lab1)
lab2 = np.asarray(lab2)
a1, b1 = np.rollaxis(lab1, -1)[1:3]
a2, b2 = np.rollaxis(lab2, -1)[1:3]
# magnitude of (a, b) is the chroma
C1 = np.hypot(a1, b1)
C2 = np.hypot(a2, b2)
term = (C1 * C2) - (a1 * a2 + b1 * b2)
return 2 * term
def _cart2polar_2pi(x, y):
"""convert cartesian coordinates to polar (uses non-standard theta range!)
NON-STANDARD RANGE! Maps to ``(0, 2*pi)`` rather than usual ``(-pi, +pi)``
"""
r, t = np.hypot(x, y), np.arctan2(y, x)
t += np.where(t < 0., 2 * np.pi, 0)
return r, t
def xy2angles(x,y):
elout = 90-np.hypot(x,y)
azout = np.degrees(np.arctan2(x,y))
return (azout,elout)
def parse(fname):
"""
Parse FGM format data *fname*. Return :class:`DataFrame`
containing all information found in the file.
The FGM file format is used by CARISMA to store data and is
described here:
http://www.carisma.ca/carisma-data/fgm-data-format.
"""
with open(fname) as fid:
siteid, lat, lon, date, pos_format, units, sample_rate = fid.next().split()
dt = []
x = []
y = []
z = []
flag = []
for line in fid:
cols = line.split()
dt.append(datetime.strptime(cols[0], '%Y%m%d%H%M%S'))
x.append(float(cols[1]))
y.append(float(cols[2]))
z.append(float(cols[3]))
if cols[4] == '.':
flag.append(False)
elif cols[4] == 'x':
flag.append(True)
else:
raise ValueError('unknown flag value {} encountered in {}'.format(cols[4], fname))
f = NP.hypot(x, NP.hypot(y, z))
df = PD.DataFrame(data={'x': x, 'y': y, 'z': z, 'f': f, 'flag': flag},
index=dt)
df.siteid = siteid
df.lat = float(lat)
df.lon = float(lon)
df.date = datetime.strptime(date, '%Y%m%d')
df.pos_format = pos_format
df.units = units
df.sample_rate = sample_rate
return df
def cart2sph(x, y, z):
'''Converts cartesian coordinates x, y, z to spherical coordinates az, el, r.'''
hxy = _np.hypot(x, y)
r = _np.hypot(hxy, z)
el = _np.arctan2(z, hxy)
az = _np.arctan2(y, x)
return az, el, r
def _vh_lines(lines, ctrs=None, lengths=None, vecs=None, angle_lo=20, angle_hi=160,
ransac_options=RANSAC_OPTIONS):
assert len(lines) > 0, "We need some lines to start with!"
ctrs = ctrs if ctrs is not None else lines.mean(1)
vecs = vecs if vecs is not None else lines[:, 1, :] - lines[:, 0, :]
lengths = lengths if lengths is not None else np.hypot(vecs[:, 0], vecs[:, 1])
return (_vlines(lines, ctrs, lengths, vecs, angle_lo, angle_hi, ransac_options=RANSAC_OPTIONS),
_hlines(lines, ctrs, lengths, vecs, angle_lo, angle_hi, ransac_options=RANSAC_OPTIONS))
def on_pick(self, event):
# Checks the lenght of the event.ind (how much points are selected)
N = len(event.ind)
# If nothing was selected - exits function
if not N:
return True
# If multiple points were selected (overlapping of the circles) - informs
# the user and exits function - needs to exit function, because not a
# unique datapoints can be (or was) selected - so no informations can
# be displayed - also throws an exception/error!
if N > 1:
print
"Multiple objects lie within selection range. Zoome in to select a single object!"
return True
# Gets the location of that click
x = event.mouseevent.xdata
y = event.mouseevent.ydata
# Calculates the distance - hypothenuse
distances = np.hypot(x - self.c[event.ind[0]], y - self.d[event.ind[0]])
# Returns the indices of the minimum values along an axis
indmin = distances.argmin()
# Gets the data index of the selected data
dataind = event.ind[indmin]
# If CTRL is pressed
if self.ctrl_on == True:
# Sets the index of the data which should be removed
self.remi = dataind
else:
# Updates the variable if no change was made
self.lastind = dataind
# Calls the update function and sets the removal variable afterwards
self.update()
self.remi = -1
# Updating the plot
def distance_between(x1, y1, x2, y2):
"""
Calculates the distance between 2 points.
"""
return np.hypot(x1 - x2, y1 - y2)
def make_dist_mat(xy1, xy2, longlat=True):
"""
Return a distance matrix between two set of coordinates.
Use geometric distance (default) or haversine distance (if longlat=True).
Parameters
----------
xy1 : numpy.array
The first set of coordinates as [(x, y), (x, y), (x, y)].
xy2 : numpy.array
The second set of coordinates as [(x, y), (x, y), (x, y)].
longlat : boolean, optionnal
Whether the coordinates are in geographic (longitude/latitude) format
or not (default: False)
Returns
-------
mat_dist : numpy.array
The distance matrix between xy1 and xy2
"""
if longlat:
return hav_dist(xy1[:, None], xy2)
else:
d0 = np.subtract.outer(xy1[:, 0], xy2[:, 0])
d1 = np.subtract.outer(xy1[:, 1], xy2[:, 1])
return np.hypot(d0, d1)
def edgedetect(channel):
sobelx = cv2.Sobel(channel, cv2.CV_16S, 1, 0, ksize=3)
sobely = cv2.Sobel(channel, cv2.CV_16S, 0, 1, ksize=3)
sobel = np.hypot(sobelx, sobely)
sobel[sobel > 255] = 255
return sobel