def make_upper_straight_line(self):
""" make upper straight line """
targetx = self.lower_concave_in_x_end
x = self.upper_convex_in_x_end
y = self.upper_convex_in_y_end
targety = np.tan(np.deg2rad(self.beta_in)) * targetx + y - np.tan(np.deg2rad(self.beta_in)) * x
self.upper_straight_in_x = [targetx, x]
self.upper_straight_in_y = [targety, y]
self.shift = - abs(self.lower_concave_in_y_end - targety)
targetx = self.lower_concave_out_x_end
x = self.upper_convex_out_x_end
y = self.upper_convex_out_y_end
targety = np.tan(np.deg2rad(self.beta_out)) * targetx + y - np.tan(np.deg2rad(self.beta_out)) * x
self.upper_straight_out_x = [targetx, x]
self.upper_straight_out_y = [targety, y]
python类tan()的实例源码
def setpointRelativeZ(self,u,v,h=0,w=0,update=False):
''' set relative height and weight of a pole point '''
u,v=v,u
#self.g[v][u][2] = self.gBase[v][u][2] + h
# unrestricted
self.g[v][u][2] = self.gBase[v][u][2] + 100* np.tan(0.5*np.pi*h/101)
sayW(("set rel h, height",h,self.g[v][u][2]))
if update:
self.gBase=self.g.copy()
try:
wl=self.obj2.weights
wl[v*self.obj2.nNodes_u+u]=w
self.obj2.weights=wl
except:
sayexc()
def publish_line(self):
# find the two points that intersect between the fan angle lines and the found y=mx+c line
x0 = self.c / (np.tan(FAN_ANGLE) - self.m)
x1 = self.c / (-np.tan(FAN_ANGLE) - self.m)
y0 = self.m*x0+self.c
y1 = self.m*x1+self.c
poly = Polygon()
p0 = Point32()
p0.y = x0
p0.x = y0
p1 = Point32()
p1.y = x1
p1.x = y1
poly.points.append(p0)
poly.points.append(p1)
polyStamped = PolygonStamped()
polyStamped.header.frame_id = "base_link"
polyStamped.polygon = poly
self.line_pub.publish(polyStamped)
def road_mapper(self, frame):
road_spots = self.road_spotter(frame)
#road_map = np.zeros(np.shape(road_spots), np.float)
#First we deal with all the points
road_map[:, 1, :] = self.camera_height * np.tan(self.camera_to_ground_arc +
road_spots[:, 0, :] * self.camera_arc_x/self.crop_ratio[1])
road_map[:, 0, :] = np.multiply( np.power( ( np.power(self.camera_height, 2) +
np.power(road_map[:, 1, :], 2) ), 0.5 ) , np.tan(self.camera_offset_y +
(road_spots[:, 1, :]-0.5)*self.camera_arc_y ) )
return road_map
# pilot_mk1 is currently only built for low speed operation
def __init__(self, pose, zmin=0.0, zmax=0.1, fov=np.deg2rad(60)):
# FoV derived from fx,fy,cx,cy=500,500,320,240
# fovx, fovy = 65.23848614 51.28201165
rx, ry = 0.638, 0.478
self.pose = pose
arr = [np.array([-rx, -ry, 1.]) * zmin,
np.array([-rx, ry, 1.]) * zmin,
np.array([ rx, ry, 1.]) * zmin,
np.array([ rx, -ry, 1.]) * zmin,
np.array([-rx, -ry, 1.]) * zmax,
np.array([-rx, ry, 1.]) * zmax,
np.array([ rx, ry, 1.]) * zmax,
np.array([ rx, -ry, 1.]) * zmax]
# vertices: nul, nll, nlr, nur, ful, fll, flr, fur
self.vertices_ = self.pose * np.vstack(arr)
# self.near, self.far = np.array([0,0,zmin]), np.array([0,0,zmax])
# self.near_off, self.far_off = np.tan(fov / 2) * zmin, np.tan(fov / 2) * zmax
# arr = [self.near + np.array([-1, -1, 0]) * self.near_off,
# self.near + np.array([1, -1, 0]) * self.near_off,
# self.near + np.array([1, 1, 0]) * self.near_off,
# self.near + np.array([-1, 1, 0]) * self.near_off,
# self.far + np.array([-1, -1, 0]) * self.far_off,
# self.far + np.array([1, -1, 0]) * self.far_off,
# self.far + np.array([1, 1, 0]) * self.far_off,
# self.far + np.array([-1, 1, 0]) * self.far_off]
# nll, nlr, nur, nul, fll, flr, fur, ful = self.pose * np.vstack(arr)
# return nll, nlr, nur, nul, fll, flr, fur, ful
def from_calib_params_fov(cls, fov, cx, cy, D=np.zeros(5, dtype=np.float64), shape=None):
return cls(construct_K(cx / np.tan(fov), cy / np.tan(fov), cx, cy), D=D, shape=shape)
def bin_stats(x, y, stat='median', nbins=360):
import scipy.stats
#bin_range = (x.min(), x.max())
bin_range = (0., 360.)
bin_width = (bin_range[1] - bin_range[0]) / nbins
print("Computing 1-degree bin statistics: %s" % stat)
bin_stat, bin_edges, bin_number = scipy.stats.binned_statistic(x, y, \
statistic=stat, bins=nbins, range=bin_range)
bin_centers = bin_edges[:-1] + bin_width/2.
bin_stat = np.ma.masked_invalid(bin_stat)
"""
#Mask bins in grid directions, can potentially contain biased stats
badbins = [0, 45, 90, 180, 225, 270, 315]
bin_stat = np.ma.masked_where(np.around(bin_edges[:-1]) % 45 == 0, bin_stat)
bin_edges = np.ma.masked_where(np.around(bin_edges[:-1]) % 45 == 0, bin_edges)
"""
#Generate plots
if False:
plt.figure()
#Need to pull out original values for each bin
#Loop through unique bin numbers, pull out original values into list of lists
#plt.boxplot(bin_stat, sym='')
plt.xlim(*bin_range)
plt.xticks(np.arange(bin_range[0],bin_range[1],30))
plt.ylabel('dh/tan(slope) (m)')
plt.xlabel('Aspect (1-deg bins)')
plt.figure()
plt.bar(bin_centers, bin_count)
plt.xlim(*bin_range)
plt.xticks(np.arange(bin_range[0],bin_range[1],30))
plt.ylabel('Count')
plt.xlabel('Aspect (1-deg bins)')
plt.show()
return bin_stat, bin_edges, bin_centers
#Function for fitting Nuth and Kaab (2011)
def pixelSize(self, pos):
"""
Return the approximate size of a screen pixel at the location pos
Pos may be a Vector or an (N,3) array of locations
"""
cam = self.cameraPosition()
if isinstance(pos, np.ndarray):
cam = np.array(cam).reshape((1,)*(pos.ndim-1)+(3,))
dist = ((pos-cam)**2).sum(axis=-1)**0.5
else:
dist = (pos-cam).length()
xDist = dist * 2. * np.tan(0.5 * self.opts['fov'] * np.pi / 180.)
return xDist / self.width()
def pixelSize(self, pos):
"""
Return the approximate size of a screen pixel at the location pos
Pos may be a Vector or an (N,3) array of locations
"""
cam = self.cameraPosition()
if isinstance(pos, np.ndarray):
cam = np.array(cam).reshape((1,)*(pos.ndim-1)+(3,))
dist = ((pos-cam)**2).sum(axis=-1)**0.5
else:
dist = (pos-cam).length()
xDist = dist * 2. * np.tan(0.5 * self.opts['fov'] * np.pi / 180.)
return xDist / self.width()
def getInscribedRectangle(self, angle, rectSz):
"""
From https://stackoverflow.com/questions/5789239/calculate-largest-rectangle-in-a-rotated-rectangle
:param angle: angle in radians
:param rectSz: rectangle size
:return:
"""
imgSzw = rectSz[0]
imgSzh = rectSz[1]
quadrant = int(numpy.floor(angle / (numpy.pi / 2.))) & 3
sign_alpha = angle if (quadrant & 1) == 0 else numpy.pi - angle
alpha = (sign_alpha % numpy.pi + numpy.pi) % numpy.pi
bbw = imgSzw * numpy.cos(alpha) + imgSzh * numpy.sin(alpha)
bbh = imgSzw * numpy.sin(alpha) + imgSzh * numpy.cos(alpha)
gamma = numpy.arctan2(bbw, bbh) if imgSzw < imgSzh else numpy.arctan2(bbh, bbw)
delta = numpy.pi - alpha - gamma
length = imgSzh if imgSzw < imgSzh else imgSzw
d = length * numpy.cos(alpha)
a = d * numpy.sin(alpha) / numpy.sin(delta)
y = a * numpy.cos(gamma)
x = y * numpy.tan(gamma)
return (int(x), int(y), int(x + bbw - 2*x), int(y + bbh - 2*y))
def hexagonal_uniform(N,as_complex=False):
'returns uniformly distributed points of shape=(2,N) within a hexagon whose minimum radius is 1.0'
phi = 2*pi/6 *.5
S = np.array( [[1,1],np.tan([phi,-phi])] ) # vectors to vertices of next hexagon ( centered at (2,0) )a
# uniformly sample the parallelogram defined by the columns of S
v = np.matmul(S,np.random.uniform(0,1,(2,N)))
v[0] = 1 - abs(v[0]-1) # fold back to make a triangle
c = (v[0] + 1j*v[1]) * np.exp( 2j*pi/6*np.floor( np.random.uniform(0,6,N) ) ) # rotate to a random sextant
if as_complex:
return c
else:
return np.array( (c.real,c.imag) )
def calc_lookahead_offset(v_ego, angle_steers, d_lookahead, angle_offset=0):
#*** this function returns the lateral offset given the steering angle, speed and the lookahead distance
curvature = calc_curvature(v_ego, angle_steers, angle_offset)
# clip is to avoid arcsin NaNs due to too sharp turns
y_actual = d_lookahead * np.tan(np.arcsin(np.clip(d_lookahead * curvature, -0.999, 0.999))/2.)
return y_actual, curvature
def test_basic_ufuncs(self):
# Test various functions such as sin, cos.
(x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d
assert_equal(np.cos(x), cos(xm))
assert_equal(np.cosh(x), cosh(xm))
assert_equal(np.sin(x), sin(xm))
assert_equal(np.sinh(x), sinh(xm))
assert_equal(np.tan(x), tan(xm))
assert_equal(np.tanh(x), tanh(xm))
assert_equal(np.sqrt(abs(x)), sqrt(xm))
assert_equal(np.log(abs(x)), log(xm))
assert_equal(np.log10(abs(x)), log10(xm))
assert_equal(np.exp(x), exp(xm))
assert_equal(np.arcsin(z), arcsin(zm))
assert_equal(np.arccos(z), arccos(zm))
assert_equal(np.arctan(z), arctan(zm))
assert_equal(np.arctan2(x, y), arctan2(xm, ym))
assert_equal(np.absolute(x), absolute(xm))
assert_equal(np.angle(x + 1j*y), angle(xm + 1j*ym))
assert_equal(np.angle(x + 1j*y, deg=True), angle(xm + 1j*ym, deg=True))
assert_equal(np.equal(x, y), equal(xm, ym))
assert_equal(np.not_equal(x, y), not_equal(xm, ym))
assert_equal(np.less(x, y), less(xm, ym))
assert_equal(np.greater(x, y), greater(xm, ym))
assert_equal(np.less_equal(x, y), less_equal(xm, ym))
assert_equal(np.greater_equal(x, y), greater_equal(xm, ym))
assert_equal(np.conjugate(x), conjugate(xm))
def test_testUfuncRegression(self):
# Tests new ufuncs on MaskedArrays.
for f in ['sqrt', 'log', 'log10', 'exp', 'conjugate',
'sin', 'cos', 'tan',
'arcsin', 'arccos', 'arctan',
'sinh', 'cosh', 'tanh',
'arcsinh',
'arccosh',
'arctanh',
'absolute', 'fabs', 'negative',
'floor', 'ceil',
'logical_not',
'add', 'subtract', 'multiply',
'divide', 'true_divide', 'floor_divide',
'remainder', 'fmod', 'hypot', 'arctan2',
'equal', 'not_equal', 'less_equal', 'greater_equal',
'less', 'greater',
'logical_and', 'logical_or', 'logical_xor',
]:
try:
uf = getattr(umath, f)
except AttributeError:
uf = getattr(fromnumeric, f)
mf = getattr(numpy.ma.core, f)
args = self.d[:uf.nin]
ur = uf(*args)
mr = mf(*args)
assert_equal(ur.filled(0), mr.filled(0), f)
assert_mask_equal(ur.mask, mr.mask, err_msg=f)
def test_testUfuncs1(self):
# Test various functions such as sin, cos.
(x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d
self.assertTrue(eq(np.cos(x), cos(xm)))
self.assertTrue(eq(np.cosh(x), cosh(xm)))
self.assertTrue(eq(np.sin(x), sin(xm)))
self.assertTrue(eq(np.sinh(x), sinh(xm)))
self.assertTrue(eq(np.tan(x), tan(xm)))
self.assertTrue(eq(np.tanh(x), tanh(xm)))
with np.errstate(divide='ignore', invalid='ignore'):
self.assertTrue(eq(np.sqrt(abs(x)), sqrt(xm)))
self.assertTrue(eq(np.log(abs(x)), log(xm)))
self.assertTrue(eq(np.log10(abs(x)), log10(xm)))
self.assertTrue(eq(np.exp(x), exp(xm)))
self.assertTrue(eq(np.arcsin(z), arcsin(zm)))
self.assertTrue(eq(np.arccos(z), arccos(zm)))
self.assertTrue(eq(np.arctan(z), arctan(zm)))
self.assertTrue(eq(np.arctan2(x, y), arctan2(xm, ym)))
self.assertTrue(eq(np.absolute(x), absolute(xm)))
self.assertTrue(eq(np.equal(x, y), equal(xm, ym)))
self.assertTrue(eq(np.not_equal(x, y), not_equal(xm, ym)))
self.assertTrue(eq(np.less(x, y), less(xm, ym)))
self.assertTrue(eq(np.greater(x, y), greater(xm, ym)))
self.assertTrue(eq(np.less_equal(x, y), less_equal(xm, ym)))
self.assertTrue(eq(np.greater_equal(x, y), greater_equal(xm, ym)))
self.assertTrue(eq(np.conjugate(x), conjugate(xm)))
self.assertTrue(eq(np.concatenate((x, y)), concatenate((xm, ym))))
self.assertTrue(eq(np.concatenate((x, y)), concatenate((x, y))))
self.assertTrue(eq(np.concatenate((x, y)), concatenate((xm, y))))
self.assertTrue(eq(np.concatenate((x, y, x)), concatenate((x, ym, x))))
def test_testUfuncRegression(self):
f_invalid_ignore = [
'sqrt', 'arctanh', 'arcsin', 'arccos',
'arccosh', 'arctanh', 'log', 'log10', 'divide',
'true_divide', 'floor_divide', 'remainder', 'fmod']
for f in ['sqrt', 'log', 'log10', 'exp', 'conjugate',
'sin', 'cos', 'tan',
'arcsin', 'arccos', 'arctan',
'sinh', 'cosh', 'tanh',
'arcsinh',
'arccosh',
'arctanh',
'absolute', 'fabs', 'negative',
'floor', 'ceil',
'logical_not',
'add', 'subtract', 'multiply',
'divide', 'true_divide', 'floor_divide',
'remainder', 'fmod', 'hypot', 'arctan2',
'equal', 'not_equal', 'less_equal', 'greater_equal',
'less', 'greater',
'logical_and', 'logical_or', 'logical_xor']:
try:
uf = getattr(umath, f)
except AttributeError:
uf = getattr(fromnumeric, f)
mf = getattr(np.ma, f)
args = self.d[:uf.nin]
with np.errstate():
if f in f_invalid_ignore:
np.seterr(invalid='ignore')
if f in ['arctanh', 'log', 'log10']:
np.seterr(divide='ignore')
ur = uf(*args)
mr = mf(*args)
self.assertTrue(eq(ur.filled(0), mr.filled(0), f))
self.assertTrue(eqmask(ur.mask, mr.mask))
def tangent(x: Number = 0.0) -> Number:
return np.tan(x)
def calc_projection_matrix(camera):
if 'perspective' in camera:
f = 1 / np.tan(camera['perspective']['yfov'] / 2)
znear, zfar = camera['perspective']['znear'], camera['perspective']['zfar']
projection_matrix = np.array([[f / camera['perspective']['aspectRatio'], 0, 0, 0],
[0, f, 0, 0],
[0, 0, (znear + zfar) / (znear - zfar), 2 * znear * zfar / (znear - zfar)],
[0, 0, -1, 0]], dtype=np.float32)
elif 'orthographic' in camera:
raise Exception('TODO')
return projection_matrix
def mk_line(n1,theta):
x = np.linspace(0,n1-1,n1)
y = np.copy(x)*0
count = 0
for t in x:
y[count] = t*np.tan(theta*np.pi/180.)
count +=1
return x,y-y[-1]/2
def daylength(dayofyear, year, latitude):
""" estimate of daylength"""
lat = numpy.radians(latitude)
dec = declination(12, dayofyear, year)
return 12 + 24 / numpy.pi * numpy.arcsin(numpy.tan(lat) - numpy.tan(dec))