def init_lats(self):
latrad = 0.0
lats = []
c = 0.5 * self.r_sight * self.safety
while latrad < pi / 2:
lats.append(latrad)
latrad += c / self.earth_R
return lats
python类pi()的实例源码
def init_grid(self):
grid_all = []
lats = self.init_lats()
c = 2 * pi / (3 ** 0.5 * self.r_sight * self.safety) * self.earth_R
even_lng = True
strip_amount = int(ceil(c))
grid_all.append((0, strip_amount, even_lng))
ind_lat = 2
while ind_lat < len(lats):
amount = int(ceil(c * cos(lats[ind_lat])))
if amount < strip_amount - (sin(lats[ind_lat]*2)*self.param_shift+self.param_stretch):
ind_lat -= 1
strip_amount = int(ceil(c * cos(lats[ind_lat])))
else:
even_lng = not even_lng
if ind_lat + 1 < len(lats):
lat = lats[ind_lat + 1] * 180 / pi
grid_all.append((lat, strip_amount, even_lng))
ind_lat += 3
grid_all.append((90.0, 1, True)) # pole
return grid_all
def cover_circle(self,loc,radius):
lat,lng = loc
output = []
r_lat = radius / earth_Rrect*180/pi
r_lng = r_lat /cos(min(abs(lat)+r_lat,90.0)*pi/180)
locations = self.cover_region((lat-r_lat,lng-r_lng),(lat+r_lat,lng+r_lng))
for location in locations:
dist = get_distance(loc,location)
if dist < radius:
output.append(location)
return output
def getCircularBounds(fitCloud=None,width=64,height=64,smoothing=0.01):
circumference = 2*(width+height)
if not fitCloud is None:
cx = np.mean(fitCloud[:,0])
cy = np.mean(fitCloud[:,1])
r = 0.5* max( np.max(fitCloud[:,0])- np.min(fitCloud[:,0]),np.max(fitCloud[:,1])- np.min(fitCloud[:,1]))
else:
r = circumference /(2.0*math.pi)
cx = cy = r
perimeterPoints = np.zeros((circumference,2),dtype=float)
for i in range(circumference):
angle = (2.0*math.pi)*float(i) / circumference - math.pi * 0.5
perimeterPoints[i][0] = cx + r * math.cos(angle)
perimeterPoints[i][1] = cy + r * math.sin(angle)
bounds = {'top':perimeterPoints[0:width],
'right':perimeterPoints[width-1:width+height-1],
'bottom':perimeterPoints[width+height-2:2*width+height-2],
'left':perimeterPoints[2*width+height-3:]}
bounds['s_top'],u = interpolate.splprep([bounds['top'][:,0], bounds['top'][:,1]],s=smoothing)
bounds['s_right'],u = interpolate.splprep([bounds['right'][:,0],bounds['right'][:,1]],s=smoothing)
bounds['s_bottom'],u = interpolate.splprep([bounds['bottom'][:,0],bounds['bottom'][:,1]],s=smoothing)
bounds['s_left'],u = interpolate.splprep([bounds['left'][:,0],bounds['left'][:,1]],s=smoothing)
return bounds
def test_import(self):
self.assert_ok("""\
import math
print(math.pi, math.e)
from math import sqrt
print(sqrt(2))
""")
def test_FileSourceTimecodeType2000Complex(self):
# Create a test file with frequency on the X-axis and time on the
# Y-axis (as one might see from an FFT)
subsize = 200
xdelta = 2.0*math.pi/subsize
ydelta = 0.125
hdr = bluefile.header(2000, 'CF', subsize=subsize)
hdr['xstart'] = -math.pi/2.0
hdr['xdelta'] = xdelta
hdr['xunits'] = 3 # frequency
hdr['ydelta'] = ydelta
hdr['yunits'] = 1 # time
data = numpy.arange(1000, dtype=numpy.complex64).reshape((-1,subsize))
self._check_FileSourceTimecode(hdr, data, subsize*2, ydelta)
def rotate(self, degrees):
# Cairo uses radians, let's be more convenient.
self.ctx.rotate(degrees * math.pi / 180)
def circle(self, xc, yc, radius):
self.arc(xc, yc, radius, 0, math.pi * 2)
def angle(self, n):
# ?? n???? ???????????
r = math.sqrt(sum(x * x for x in self[n:]))
a = math.atan2(r, self[n - 1])
if (n == len(self)) and (self[-1] < 0):
return math.pi * 2 - a
else:
return a
def createLabels(X, y, labels, cameraObj=None):
labelIndices = set(y)
objects = []
# Draw labels
for labelIdx in labelIndices:
center = np.sum([x for x, idx in zip(X, y) \
if idx == labelIdx], axis=0)
counts = (y == labelIdx).sum()
center = Vector(center) / counts
label = labels[labelIdx]
fontCurve = bpy.data.curves.new(type="FONT", name=label)
fontCurve.body = label
fontCurve.align_x = 'CENTER'
fontCurve.align_y = 'BOTTOM'
fontCurve.size = 0.6
obj = bpy.data.objects.new("Label {}".format(label), fontCurve)
obj.location = center + Vector((0, 0, 0.8))
obj.rotation_mode = 'AXIS_ANGLE'
obj.rotation_axis_angle = (pi/2, 1, 0, 0)
bpy.context.scene.objects.link(obj)
if cameraObj is not None:
constraint = obj.constraints.new('LOCKED_TRACK')
constraint.target = cameraObj
constraint.track_axis = 'TRACK_Z'
constraint.lock_axis = 'LOCK_Y'
objects.append(obj)
bpy.context.scene.update()
return objects
def __init__(self, scene):
self.n, self.m = 40, 30
self.r0, self.r1, self.r2 = 10, 2, 2
self.h0, self.h1 = 10, 3
self.frames = scene.frame_end - scene.frame_start + 1
# Calculate and compensate for angle offset for infinite animation
self.offset = (self.frames * goldenAngle) % TAU
if self.offset > pi: self.offset -= TAU
# Create object
mesh = bpy.data.meshes.new('PhyllotaxisFlower')
self.obj = bpy.data.objects.new('PhyllotaxisFlower', mesh)
# Create mesh
bm = self.geometry()
bm.to_mesh(mesh)
mesh.update()
bm.free()
# Link object to scene
scene.objects.link(self.obj)
scene.update()
# Append new frame change handler to redraw geometry
# for each frame change
bpy.app.handlers.frame_change_pre.append(self.__frameChangeHandler)
def geometry(self, frame=0):
t = frame / self.frames
Rot = Matrix.Rotation(0.5*pi, 4, 'Y')
bm = bmesh.new()
for i in range(self.n):
t0 = i / self.n
r0, theta = t0*self.r0, i*goldenAngle - frame*goldenAngle + t*self.offset
x = r0*cos(theta)
y = r0*sin(theta)
z = self.h0/2 - (self.h0 / (self.r0*self.r0))*r0*r0
p0 = Vector((x, y, z))
T0, N0, B0 = getTNBfromVector(p0)
M0 = Matrix([T0, B0, N0]).to_4x4().transposed()
for j in range(self.m):
t1 = j / self.m
t2 = 0.4 + 0.6*t0
r1, theta = t2*t1*self.r1, j*goldenAngle #- frame*goldenAngle + t*self.offset
x = r1*cos(theta)
y = r1*sin(theta)
z = self.h1 - (self.h1 / (self.r1*self.r1))*r1*r1
p1 = Vector((x, y, z))
T1, N1, B1 = getTNBfromVector(p1)
M1 = Matrix([T1, B1, N1]).to_4x4().transposed()
p = p0 + M0*p1
r2 = t2*t1*self.r2
T = Matrix.Translation(p)
bmesh.ops.create_cone(bm,
cap_ends=True, segments=6,
diameter1=r2, diameter2=r2,
depth=0.1*r2, matrix=T*M0*M1*Rot)
return bm
def __log_likelihood_factor__(self, samples_q, v_noise, X, wb, y):
# Account for occasions where we're optimizing the latent weighting distributions
if wb.shape[0] == 1:
if wb.shape[1] > self.num_latent_params: # Further account
# Reshape the wb to be a full matrix and build full latent array
Wb = np.reshape(wb, [-1,self.num_latent_params])
latent_weights = np.array([Wb[int(X[tt,-1]),:] for tt in range(X.shape[0])])
outputs = self.__predict__(samples_q, np.hstack([X[:,:-1], latent_weights]))
else:
outputs = self.__predict__(samples_q, np.hstack([X, np.tile(wb,(X.shape[0],1))]))
else:
outputs = self.__predict__(samples_q, np.hstack([X, wb]))
return (-0.5*np.log(2*math.pi*v_noise)) - (0.5*(np.tile(np.expand_dims(y,axis=0), (self.num_weight_samples,1,1))-outputs)**2)/v_noise
def __log_normalizer__(self, q):
return np.sum(0.5*np.log(q['v']*2*math.pi) + 0.5*q['m']**2/q['v'])
def __log_Z_prior__(self):
return self.num_weights * 0.5 * np.log(self.v_prior*2*math.pi)
def get_error_and_ll(self, X, y, location, scale):
v_noise = np.exp(self.parser.get(self.weights, 'log_v_noise')[0,0]) * scale**2
q = self.__get_parameters_q__()
samples_q = self.__draw_samples__(q)
outputs = self.__predict__(samples_q, X)
log_factor = -0.5*np.log(2*math.pi*v_noise) - 0.5*(np.tile(np.expand_dims(y,axis=0), (self.num_weight_samples,1,1))-np.array(outputs))**2/v_noise
ll = np.mean(logsumexp(np.sum(log_factor,2)-np.log(self.num_weight_samples), 0))
error = np.sqrt(np.mean((y-np.mean(outputs, axis=0))**2))
return error, ll
def show_result(hists, bin_edges):
""" check results """
for b_edge in bin_edges/math.pi*180:
print '{0:.2f}\t'.format(round(b_edge)),
print
for hist in hists:
print '{0:.2f}\t'.format(hist),
print
def gradient_histogram(flow_img, binsize=12):
""" calculate histogram """
assert len(flow_img.shape) == 3, "Wrong flow image."
# NOTE the frame is in RGB, while cv2 is in BGR, so do REMEMBER to reverse it.
img_mag, img_v, img_u = np.split(flow_img, 3, 2)
# NOTE the role reversal: the "y-coordinate" is the first function parameter, the "x-coordinate" is the second.
# NOTE that we use same axis configure as image axis(x is larger to the right, y is larger to the bottom),
# so add a minus sign before img_v, to make the two axis align.
orientation = np.arctan2(-img_v, img_u)
# Original result not applicable
# Directly use full 360 degree
new_orient = orientation
# Prune zero motion
_mag_greater_zero = img_mag > 0.0
pruned_orient = new_orient[_mag_greater_zero]
# Histogram of optical flow
hofbins = np.arange(-math.pi, math.pi+1e-6, 2*math.pi/binsize)
hist, bin_edges = np.histogram(pruned_orient.flatten(), bins= hofbins) #, density=True)
# Normalize
hist = hist.astype(np.float32) / (np.sum(_mag_greater_zero) + 1e-6)
return hist, bin_edges
def cart2polar(x, y, degrees=True):
"""
Convert cartesian X and Y to polar RHO and THETA.
:param x: x cartesian coordinate
:param y: y cartesian coordinate
:param degrees: True = return theta in degrees, False = return theta in
radians. [default: True]
:return: r, theta
"""
rho = ma.sqrt(x ** 2 + y ** 2)
theta = ma.arctan2(y, x)
if degrees:
theta *= (180 / math.pi)
return rho, theta
uncovered.py 文件源码
项目:Daniel-Arbuckles-Mastering-Python
作者: PacktPublishing
项目源码
文件源码
阅读 27
收藏 0
点赞 0
评论 0
def degrees(radians):
return 180 * (radians / math.pi)