def haversine(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * asin(sqrt(a))
km = 6367 * c
return km
python类sin()的实例源码
def test_send():
btl = BluetoothLogger(fields=["speed", "rpm", "soc"], password=password)
btl.start()
# generate some data and send it
x = range(1000)
y = map(lambda v: sin(v * pi / 45) * 5000 + 5000, x)
speeds = cycle(y)
print("Sending dummy data")
while 1:
try:
row = map(str, [round(next(speeds), 2), 5000, 50])
btl.send(",".join(row))
time.sleep(1)
except KeyboardInterrupt:
print("Terminating")
break
btl.join()
def get_motion_vector(self):
"""Returns the current motion vector indicating the velocity of the player.
Returns
-------
vector : tuple of len 3
Tuple containing the velocity in x, y, and z respectively.
"""
if any(self.strafe):
x, y = self.rotation
strafe = math.degrees(math.atan2(*self.strafe))
y_angle = math.radians(y)
x_angle = math.radians(x + strafe)
if self.flying:
m = math.cos(y_angle)
dy = math.sin(y_angle)
if self.strafe[1]:
# Moving left or right.
dy = 0.0
m = 1
if self.strafe[0] > 0:
# Moving backwards.
dy *= -1
# When you are flying up or down, you have less left and right motion.
dx = math.cos(x_angle) * m
dz = math.sin(x_angle) * m
else:
dy = 0.0
dx = math.cos(x_angle)
dz = math.sin(x_angle)
else:
dy = 0.0
dx = 0.0
dz = 0.0
dy += self.strafe_z
return dx, dy, dz
def get_sight_vector(self):
"""Returns the current line of sight vector indicating the direction the
player is looking.
"""
x, y = self.rotation
# y ranges from -90 to 90, or -pi/2 to pi/2, so m ranges from 0 to 1 and
# is 1 when looking ahead parallel to the ground and 0 when looking
# straight up or down.
m = math.cos(math.radians(y))
# dy ranges from -1 to 1 and is -1 when looking straight down and 1 when
# looking straight up.
dy = math.sin(math.radians(y))
dx = math.cos(math.radians(x - 90)) * m
dz = math.sin(math.radians(x - 90)) * m
return dx, dy, dz
def set_3d(self, size):
"""Configure OpenGL to draw in 3d."""
width, height = size
GL.glEnable(GL.GL_DEPTH_TEST)
GL.glViewport(0, 0, width, height)
GL.glMatrixMode(GL.GL_PROJECTION)
GL.glLoadIdentity()
GL.gluPerspective(65.0, width / float(height), 0.1, 60.0)
GL.glMatrixMode(GL.GL_MODELVIEW)
GL.glLoadIdentity()
x, y = self.player.rotation
GL.glRotatef(x, 0, 1, 0)
GL.glRotatef(-y, math.cos(math.radians(x)), 0, math.sin(math.radians(x)))
x, y, z = self.player.position
GL.glTranslatef(-x, -y, -z)
def interpolate(self, other, this_weight):
q0, q1 = np.roll(self.q, shift=1), np.roll(other.q, shift=1)
u = 1 - this_weight
assert(u >= 0 and u <= 1)
cos_omega = np.dot(q0, q1)
if cos_omega < 0:
result = -q0[:]
cos_omega = -cos_omega
else:
result = q0[:]
cos_omega = min(cos_omega, 1)
omega = math.acos(cos_omega)
sin_omega = math.sin(omega)
a = math.sin((1-u) * omega)/ sin_omega
b = math.sin(u * omega) / sin_omega
if abs(sin_omega) < 1e-6:
# direct linear interpolation for numerically unstable regions
result = result * this_weight + q1 * u
result /= math.sqrt(np.dot(result, result))
else:
result = result*a + q1*b
return Quaternion(np.roll(result, shift=-1))
# To conversions
def to_angle_axis(self):
""" Return axis-angle representation """
q = np.roll(self.q, shift=1)
halftheta = math.acos(q[0])
if abs(halftheta) < 1e-12:
return 0, np.array((0, 0, 1))
else:
theta = halftheta * 2
axis = np.array(q[1:4]) / math.sin(halftheta)
return theta, axis
def from_angle_axis(cls, theta, axis):
""" Construct Quaternion from axis-angle representation """
x, y, z = axis
norm = math.sqrt(x*x + y*y + z*z)
if 0 == norm:
return cls([0, 0, 0, 1])
t = math.sin(theta/2) / norm;
return cls([x*t, y*t, z*t, math.cos(theta/2)])
# Properties
def orthogonalization_matrix(lengths, angles):
"""Return orthogonalization matrix for crystallographic cell coordinates.
Angles are expected in degrees.
The de-orthogonalization matrix is the inverse.
>>> O = orthogonalization_matrix((10., 10., 10.), (90., 90., 90.))
>>> numpy.allclose(O[:3, :3], numpy.identity(3, float) * 10)
True
>>> O = orthogonalization_matrix([9.8, 12.0, 15.5], [87.2, 80.7, 69.7])
>>> numpy.allclose(numpy.sum(O), 43.063229)
True
"""
a, b, c = lengths
angles = numpy.radians(angles)
sina, sinb, _ = numpy.sin(angles)
cosa, cosb, cosg = numpy.cos(angles)
co = (cosa * cosb - cosg) / (sina * sinb)
return numpy.array((
( a*sinb*math.sqrt(1.0-co*co), 0.0, 0.0, 0.0),
(-a*sinb*co, b*sina, 0.0, 0.0),
( a*cosb, b*cosa, c, 0.0),
( 0.0, 0.0, 0.0, 1.0)),
dtype=numpy.float64)
def quaternion_about_axis(angle, axis):
"""Return quaternion for rotation about axis.
>>> q = quaternion_about_axis(0.123, (1, 0, 0))
>>> numpy.allclose(q, [0.06146124, 0, 0, 0.99810947])
True
"""
quaternion = numpy.zeros((4, ), dtype=numpy.float64)
quaternion[:3] = axis[:3]
qlen = vector_norm(quaternion)
if qlen > _EPS:
quaternion *= math.sin(angle/2.0) / qlen
quaternion[3] = math.cos(angle/2.0)
return quaternion
def quaternion_slerp(quat0, quat1, fraction, spin=0, shortestpath=True):
"""Return spherical linear interpolation between two quaternions.
>>> q0 = random_quaternion()
>>> q1 = random_quaternion()
>>> q = quaternion_slerp(q0, q1, 0.0)
>>> numpy.allclose(q, q0)
True
>>> q = quaternion_slerp(q0, q1, 1.0, 1)
>>> numpy.allclose(q, q1)
True
>>> q = quaternion_slerp(q0, q1, 0.5)
>>> angle = math.acos(numpy.dot(q0, q))
>>> numpy.allclose(2.0, math.acos(numpy.dot(q0, q1)) / angle) or \
numpy.allclose(2.0, math.acos(-numpy.dot(q0, q1)) / angle)
True
"""
q0 = unit_vector(quat0[:4])
q1 = unit_vector(quat1[:4])
if fraction == 0.0:
return q0
elif fraction == 1.0:
return q1
d = numpy.dot(q0, q1)
if abs(abs(d) - 1.0) < _EPS:
return q0
if shortestpath and d < 0.0:
# invert rotation
d = -d
q1 *= -1.0
angle = math.acos(d) + spin * math.pi
if abs(angle) < _EPS:
return q0
isin = 1.0 / math.sin(angle)
q0 *= math.sin((1.0 - fraction) * angle) * isin
q1 *= math.sin(fraction * angle) * isin
q0 += q1
return q0
def random_quaternion(rand=None):
"""Return uniform random unit quaternion.
rand: array like or None
Three independent random variables that are uniformly distributed
between 0 and 1.
>>> q = random_quaternion()
>>> numpy.allclose(1.0, vector_norm(q))
True
>>> q = random_quaternion(numpy.random.random(3))
>>> q.shape
(4,)
"""
if rand is None:
rand = numpy.random.rand(3)
else:
assert len(rand) == 3
r1 = numpy.sqrt(1.0 - rand[0])
r2 = numpy.sqrt(rand[0])
pi2 = math.pi * 2.0
t1 = pi2 * rand[1]
t2 = pi2 * rand[2]
return numpy.array((numpy.sin(t1)*r1,
numpy.cos(t1)*r1,
numpy.sin(t2)*r2,
numpy.cos(t2)*r2), dtype=numpy.float64)
def applyLinearTransformToCoords(self, coords, angle, shear_x, shear_y, scale, \
size_in, size_out):
'''Apply the image transformation specified by three parameters to a list of
coordinates. The anchor point of the transofrmation is the center of the tile.
Args:
x: list of coordinates.
angle: Angle by which the image is rotated.
shear_x: Shearing factor along the x-axis by which the image is sheared.
shear_y: Shearing factor along the x-axis by which the image is sheared.
scale: Scaling factor by which the image is scaled.
Returns:
A list of transformed coordinates.
'''
s_in = (size_in, size_in)
s_out = (size_out, size_out)
c_in = .5 * np.asarray(s_in, dtype=np.float64).reshape((1, 2))
c_out = .5 * np.asarray(s_out, dtype=np.float64).reshape((1, 2))
M_rot = np.asarray([[math.cos(angle), -math.sin(angle)], \
[math.sin(angle), math.cos(angle)]])
M_shear = np.asarray([[1., shear_x], [shear_y, 1.]])
M = np.dot(M_rot, M_shear)
M *= scale # Without translation, it does not matter whether scale is
# applied first or last.
coords = coords.astype(np.float64)
coords -= c_in
coords = np.dot(M.T, coords.T).T
coords += c_out
return np.round(coords).astype(np.int32)
# tf augmentation methods
# TODO https://github.com/tensorflow/benchmarks/blob/master/scripts/tf_cnn_benchmarks/preprocessing.py
def sine(middle, pos):
return (sin((-pi / 2.0) + pi * linear(middle, pos)) + 1.0) / 2.0
def rotate(self, angle):
"""Return a new transformation, rotated by 'angle' (radians).
Example:
>>> import math
>>> t = Transform()
>>> t.rotate(math.pi / 2)
<Transform [0 1 -1 0 0 0]>
>>>
"""
import math
c = _normSinCos(math.cos(angle))
s = _normSinCos(math.sin(angle))
return self.transform((c, s, -s, c, 0, 0))
def img_affine_aug_pipeline_2d(img, op_str='rts', rotate_angle_range=5, translate_range=3, shear_range=3, random_mode=True, probability=0.5):
if random_mode:
if random.random() < 0.5:
return img
mat = np.identity(3)
for op in op_str:
if op == 'r':
rad = math.radian(((random.random() * 2) - 1) * rotate_angle_range)
cos = math.cos(rad)
sin = math.sin(rad)
rot_mat = np.identity(3)
rot_mat[0][0] = cos
rot_mat[0][1] = sin
rot_mat[1][0] = -sin
rot_mat[1][1] = cos
mat = np.dot(mat, rot_mat)
elif op == 't':
dx = ((random.random() * 2) - 1) * translate_range
dy = ((random.random() * 2) - 1) * translate_range
shift_mat = np.identity(3)
shift_mat[0][2] = dx
shift_mat[1][2] = dy
mat = np.dot(mat, shift_mat)
elif op == 's':
dx = ((random.random() * 2) - 1) * shear_range
dy = ((random.random() * 2) - 1) * shear_range
shear_mat = np.identity(3)
shear_mat[0][1] = dx
shear_mat[1][0] = dy
mat = np.dot(mat, shear_mat)
else:
continue
affine_mat = np.array([mat[0], mat[1]])
return apply_affine(img, affine_mat), affine_mat
def setup(self):
pl = Plot(self.size, [-4, 4, -1.5, 1.5]).config(bg="white")
pl.series(sin, param=[-pi, pi, 2 * self.width - 1], marker=("blue", 4))
self.bg = pl.snapshot()
robo = Robot(["#ff5050", "#ffd428"])
self["Traci"] = self.bindBrain(robo).config(width=60, pos=self.center)
def vec2d(r, a, deg=True):
"2D Polar to Cartesian conversion"
if deg: a *= DEG
return r * cos(a), r * sin(a)
def _matrix(rotate=0, scale=1, rev=False):
"Create a 2x2 matrix (as a 4-tuple) to perform a scale transformation and a rotation"
sx, sy = (scale, scale) if type(scale) in (float, int) else scale
if rotate:
rotate *= DEG
c, s = cos(rotate), sin(rotate)
else: c, s = 1, 0
if rev: # Rotate before scaling
return sx * c, -sx * s, sy * s, sy * c
else: # Scale before rotating
return sx * c, -sy * s, sx * s, sy * c
def generate_points(width, height):
amp = 5 # radius fillet
width += 2
height += 4
width = ((width/2) - amp) + 2
height -= (2*amp)
pos_list, final_list = [], []
n_points = 12
seg_angle = 2 * math.pi / n_points
for i in range(n_points + 1):
angle = i * seg_angle
x = math.cos(angle) * amp
y = math.sin(angle) * amp
pos_list.append([x, -y])
w_list, h_list = [1, -1, -1, 1], [-1, -1, 1, 1]
slice_list = [[i, i+4] for i in range(0, n_points, 3)]
for idx, (start, end) in enumerate(slice_list):
point_array = pos_list[start:end]
w = width * w_list[idx]
h = height * h_list[idx]
final_list += adjust_list(point_array, w, h)
return final_list