我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用math.pi()。
def neighbor_circle(location, pos, shift=False, factor=1.0): pos = pos % 6 latrad = location[0] * pi / 180 x_un = factor * safety / earth_Rrect / cos(latrad) * 180 / pi y_un = factor * safety / earth_Rrect * 180 / pi if not shift: y_un = y_un * (3.0 ** 0.5) / 2.0 * HEX_R x_un = x_un * HEX_R * 1.5 yvals = [-2, -1, 1, 2, 1, -1] xvals = [0, 1, 1, 0, -1, -1] else: y_un = y_un * HEX_R * 1.5 x_un = x_un * (3.0 ** 0.5) / 2.0 * HEX_R yvals = [-1, 0, 1, 1, 0, -1] xvals = [1, 2, 1, -1, -2, -1] newlat = location[0] + y_un * yvals[pos] newlng = ((location[1] + x_un * xvals[pos] + 180) % 360) - 180 return (newlat, newlng)
def getBestCircularMatch(n): bestc = n*2 bestr = 0 bestrp = 0.0 minr = int(math.sqrt(n / math.pi)) for rp in range(0,10): rpf = float(rp)/10.0 for r in range(minr,minr+3): rlim = (r+rpf)*(r+rpf) c = 0 for y in range(-r,r+1): yy = y*y for x in range(-r,r+1): if x*x+yy<rlim: c+=1 if c == n: return r,rpf,c if c>n and c < bestc: bestrp = rpf bestr = r bestc = c return bestr,bestrp,bestc
def flow_orientation(orientation): """ Currently not use anymore """ # Boolean map _greater_pi = orientation > math.pi/2 _less_minuspi = orientation < -math.pi/2 _remaining_part = ~(_greater_pi & _less_minuspi) # orientation map greater_pi = orientation*_greater_pi less_minuspi = orientation*_less_minuspi remaining_part = orientation*_remaining_part pi_map = math.pi * np.ones(orientation.shape) # converted orientation map convert_greater_pi = pi_map*_greater_pi - greater_pi convert_less_minuspi = -pi_map*_less_minuspi - less_minuspi new_orient = remaining_part + convert_greater_pi + convert_less_minuspi return new_orient
def angle_wrap(angle,radians=False): ''' Wraps the input angle to 360.0 degrees. if radians is True: input is assumed to be in radians, output is also in radians ''' if radians: wrapped = angle % (2.0*PI) if wrapped < 0.0: wrapped = 2.0*PI + wrapped else: wrapped = angle % 360.0 if wrapped < 0.0: wrapped = 360.0 + wrapped return wrapped
def _compute(self): """Compute r min max and labels position""" delta = 2 * pi / self._len if self._len else 0 self._x_pos = [.5 * pi + i * delta for i in range(self._len + 1)] for serie in self.all_series: serie.points = [ (v, self._x_pos[i]) for i, v in enumerate(serie.values)] if self.interpolate: extended_x_pos = ( [.5 * pi - delta] + self._x_pos) extended_vals = (serie.values[-1:] + serie.values) serie.interpolated = list( map(tuple, map(reversed, self._interpolate( extended_x_pos, extended_vals)))) # x labels space self._box.margin *= 2 self._rmin = self.zero self._rmax = self._max or 1 self._box.set_polar_box(self._rmin, self._rmax) self._self_close = True
def spectralBlackBody(Lambda=0.7, T=5800): """ here is the explanation of this function""" import math c0 = 2.9979*10**8 #m/s speed of light in vacuum h_Plank=6.626069*10**-34 #J.s Plank's Constant sigma_stefan_Boltzmann= 5.67*10**-8 #Stefan-Boltzmann Constant n=1 #the index of refraction of that medium c=c0/n# the speed of propagation of a wave in the medium F=c/Lambda #the frequency of the wave e_wave=h_Plank*F E_blackBody = sigma_stefan_Boltzmann*T**4 k_Boltzmann=1.38065*10**-23 #J/K Boltzmann Constant #Plank's Law: C1=2*math.pi*h_Plank*c0**2*(10**24)#J*s*m^2/s^2--W*m2 --->W C2=h_Plank*c0/k_Boltzmann*(10**6) #microm m/K EmissiveSpectral= C1/(Lambda**5*(math.exp(C2/(Lambda*T))-1)) outPut = {"EmissiveSpectral":EmissiveSpectral,"E_blackBody":E_blackBody} return outPut
def get_directed_hausdorff_distance(self, other): if other.contains(self): return 0.0 if other.is_empty(): return math.pi other_complement_center = other.get_complement_center() if self.contains(other_complement_center): return self.__class__.positive_distance(other.hi(), other_complement_center) else: if self.__class__(other.hi(), other_complement_center) \ .contains(self.hi()): hi_hi = self.__class__.positive_distance(other.hi(), self.hi()) else: hi_hi = 0 if self.__class__(other_complement_center, other.lo()) \ .contains(self.lo()): lo_lo = self.__class__.positive_distance(self.lo(), other.lo()) else: lo_lo = 0 assert hi_hi > 0 or lo_lo > 0 return max(hi_hi, lo_lo)
def testConstructorsAndAccessors(self): self.assertEqual(self.quad12.lo(), 0) self.assertEqual(self.quad12.hi(), math.pi) self.assertEqual(self.quad34.bound(0), math.pi) self.assertEqual(self.quad34.bound(1), 0) self.assertEqual(self.pi.lo(), math.pi) self.assertEqual(self.pi.hi(), math.pi) # Check that [-Pi, -Pi] is normalized to [Pi, Pi]. self.assertEqual(self.mipi.lo(), math.pi) self.assertEqual(self.mipi.hi(), math.pi) self.assertEqual(self.quad23.lo(), math.pi / 2.0) self.assertEqual(self.quad23.hi(), -math.pi / 2.0) default_empty = SphereInterval() self.assertTrue(default_empty.is_valid()) self.assertTrue(default_empty.is_empty()) self.assertEqual(self.empty.lo(), default_empty.lo()) self.assertEqual(self.empty.hi(), default_empty.hi()) # Should check intervals can be modified here
def testSimplePredicates(self): # is_valid(), is_empty(), is_full(), is_inverted() self.assertTrue(self.zero.is_valid() and not self.zero.is_empty() and not self.zero.is_full()) self.assertTrue(self.empty.is_valid() and self.empty.is_empty() and not self.empty.is_full()) self.assertTrue(self.empty.is_inverted()) self.assertTrue(self.full.is_valid() and not self.full.is_empty() and self.full.is_full()) self.assertTrue(not self.quad12.is_empty() and not self.quad12.is_full() and not self.quad12.is_inverted()) self.assertTrue(not self.quad23.is_empty() and not self.quad23.is_full() and self.quad23.is_inverted()) self.assertTrue(self.pi.is_valid() and not self.pi.is_empty() and not self.pi.is_inverted()) self.assertTrue(self.mipi.is_valid() and not self.mipi.is_empty() and not self.mipi.is_inverted())
def testApproxEquals(self): self.assertTrue(self.empty.approx_equals(self.empty)) self.assertTrue(self.zero.approx_equals(self.empty) and self.empty.approx_equals(self.zero)) self.assertTrue(self.pi.approx_equals(self.empty) and self.empty.approx_equals(self.pi)) self.assertTrue(self.mipi.approx_equals(self.empty) and self.empty.approx_equals(self.mipi)) self.assertTrue(self.pi.approx_equals(self.mipi) and self.mipi.approx_equals(self.pi)) self.assertTrue(self.pi.union(self.mipi).approx_equals(self.pi)) self.assertTrue(self.mipi.union(self.pi).approx_equals(self.pi)) self.assertTrue(self.pi.union( self.mid12).union(self.zero).approx_equals(self.quad12)) self.assertTrue(self.quad2.intersection( self.quad3).approx_equals(self.pi)) self.assertTrue(self.quad3.intersection( self.quad2).approx_equals(self.pi))
def testGetVertex(self): r1 = LatLngRect(LineInterval(0, math.pi / 2.0), SphereInterval(-math.pi, 0)) self.assertEqual(r1.get_vertex(0), LatLng.from_radians(0, math.pi)) self.assertEqual(r1.get_vertex(1), LatLng.from_radians(0, 0)) self.assertEqual(r1.get_vertex(2), LatLng.from_radians(math.pi / 2.0, 0)) self.assertEqual(r1.get_vertex(3), LatLng.from_radians(math.pi / 2.0, math.pi)) # Make sure the get_vertex() returns vertices in CCW order. for i in range(4): lat = math.pi / 4.0 * (i - 2) lng = math.pi / 2.0 * (i - 2) + 0.2 r = LatLngRect(LineInterval(lat, lat + math.pi / 4.0), SphereInterval(s2sphere.drem(lng, 2 * math.pi), s2sphere.drem(lng + math.pi / 2.0, 2 * math.pi))) for k in range(4): self.assertTrue( s2sphere.simple_ccw(r.get_vertex((k - 1) & 3).to_point(), r.get_vertex(k).to_point(), r.get_vertex((k + 1) & 3).to_point()) )
def get_angle_formed_by(p1,p2,p3): # angle formed by three positions in space # based on code submitted by Paul Sherwood r1 = distance(p1,p2) r2 = distance(p2,p3) r3 = distance(p1,p3) small = 1.0e-10 if (r1 + r2 - r3) < small: # This seems to happen occasionally for 180 angles theta = math.pi else: theta = math.acos( (r1*r1 + r2*r2 - r3*r3) / (2.0 * r1*r2) ) return theta; #------------------------------------------------------------------------------
def mitsuta_mean(self, angles_array): # Function meant to work with degrees, covert inputs # from radians to degrees and output from degrees to radians D = math.degrees(angles_array[0]) mysum = D for val in angles_array[1:]: val = math.degrees(val) delta = val - D if delta < -180.0: D = D + delta + 360.0 elif delta < 180.0: D = D + delta else: D = D + delta - 360.0 mysum = mysum + D m = mysum / len(angles_array) avg = math.radians((m + 360.0) % 360.0) # make sure avg is between -pi and pi if avg > math.pi: avg = avg - 2.0 * math.pi elif avg < -math.pi: avg = avg + 2.0 * math.pi return avg
def distance(latitude_1, longitude_1, elevation_1, latitude_2, longitude_2, elevation_2, haversine=None): """ Distance between two points """ # If points too distant -- compute haversine distance: if haversine or (abs(latitude_1 - latitude_2) > .2 or abs(longitude_1 - longitude_2) > .2): return haversine_distance(latitude_1, longitude_1, latitude_2, longitude_2) coef = math.cos(latitude_1 / 180. * math.pi) #pylint: disable=invalid-name x = latitude_1 - latitude_2 y = (longitude_1 - longitude_2) * coef distance_2d = math.sqrt(x * x + y * y) * ONE_DEGREE if elevation_1 is None or elevation_2 is None or elevation_1 == elevation_2: return distance_2d return math.sqrt(distance_2d ** 2 + (elevation_1 - elevation_2) ** 2)
def ComputeCoverage(sigma_points, bias): def ang(p): v = rotvecquat(vector.sub(p.compass, bias), vec2vec2quat(p.down, [0, 0, 1])) return math.atan2(v[1], v[0]) angles = sorted(map(ang, sigma_points)) #print 'angles', angles max_diff = 0 for i in range(len(angles)): diff = -angles[i] j = i+1 if j == len(angles): diff += 2*math.pi j = 0 diff += angles[j] max_diff = max(max_diff, diff) return max_diff
def onMouseEventsBoatPlot( self, event ): self.BoatPlot.SetFocus() pos = event.GetPosition() if event.LeftDown(): self.lastmouse = pos if event.Dragging(): dx, dy = pos[0] - self.lastmouse[0], pos[1] - self.lastmouse[1] q = pypilot.quaternion.angvec2quat((dx**2 + dy**2)**.4/180*math.pi, [dy, dx, 0]) self.boat_plot.Q = pypilot.quaternion.multiply(q, self.boat_plot.Q) self.BoatPlot.Refresh() self.lastmouse = pos rotation = event.GetWheelRotation() / 60 if rotation: self.BoatPlot.Refresh() while rotation > 0: self.boat_plot.Scale /= .9 rotation -= 1 while rotation < 0: self.boat_plot.Scale *= .9 rotation += 1
def __init__(self,seed): random.seed(seed) self.ISLAND_FACTOR = 1.13 # 1.0 means no small islands; 2.0 leads to a lot self.bumps = random.randrange(1,7) self.startAngle = random.uniform(0,2*math.pi) self.dipAngle = random.uniform(0,2*math.pi) self.dipWidth = random.uniform(0.2,0.7)
def __init__(self): self.ser = serial.Serial('/dev/ttyACM0', 9600) #geometrical calibration self.rs = [50, 50, 50] self.ls = [95, 130, 95] self.pot_rad_per_unit = 1./3000.*math.pi angles = [2./3.*math.pi, 0., -2./3.*math.pi] #placements of the 3 joysticks self.placements = [] #attach point on the ball self.attach_ps = [] for r,l,a in zip(self.rs, self.ls, angles): p_init = pose.exp(col([0, 0, 0, 0, 0, -(r+l)])) p_rot = pose.exp(col([0, a, 0, 0, 0, 0])) placement = p_rot * p_init self.placements.append(placement) attach_p = placement * col([0, 0, l]) self.attach_ps.append(attach_p) #last calculated pose in logarithmic coordinates self.last_x = col([0, 0, 0, 0, 0, 0]) #definition of the numerical solver f = lambda x: self.getValuesFromPose(pose.exp(x)) self.solver = solver.Solver(f)
def __init__(self, model, action_size=1, init_value=0.0, *args, **kwargs): super(DiagonalGaussianPolicy, self).__init__(model, *args, **kwargs) self.init_value = init_value self.logstd = th.zeros((1, action_size)) + self.init_value self.logstd = P(self.logstd) self.halflog2pie = V(T([2 * pi * exp(1)])) * 0.5 self.halflog2pi = V(T([2.0 * pi])) * 0.5 self.pi = V(T([pi]))
def _normal(self, x, mean, logstd): std = logstd.exp() std_sq = std.pow(2) a = (-(x - mean).pow(2) / (2 * std_sq)).exp() b = (2 * std_sq * self.pi.expand_as(std_sq)).sqrt() return a / b
def rokuro_add_euler(euler, r): props = bpy.context.window_manager.rokuro if props.rotate_direction: if (euler + r) < 0: new_euler = euler + r + (2.0 * math.pi) else: new_euler = euler + r else: if (euler + r) > (2.0 * math.pi): new_euler = euler + r - (2.0 * math.pi) else: new_euler = euler + r return new_euler
def rokuro_proc(scene): props = bpy.context.window_manager.rokuro r = props.rotate_step * 2.0 * math.pi / (scene.frame_end - scene.frame_start) if props.rotate_direction: r *= -1.0 if props.rotate_axis_x: bpy.context.object.rotation_euler[0] = rokuro_add_euler(bpy.context.object.rotation_euler[0], r) if props.rotate_axis_y: bpy.context.object.rotation_euler[1] = rokuro_add_euler(bpy.context.object.rotation_euler[1], r) if props.rotate_axis_z: bpy.context.object.rotation_euler[2] = rokuro_add_euler(bpy.context.object.rotation_euler[2], r)
def drag_bone(self,context, event ,bone=None): ### math.atan2(0.5, 0.5)*180/math.pi if bone != None: bone.hide = False mouse_vec_norm = (self.cursor_location - self.mouse_click_vec).normalized() mouse_vec = (self.cursor_location - self.mouse_click_vec) angle = (math.atan2(mouse_vec_norm[0], mouse_vec_norm[2])*180/math.pi) cursor_local = self.armature.matrix_world.inverted() * self.cursor_location cursor_local[1] = 0 if event.shift: if angle > -22.5 and angle < 22.5: ### up bone.tail = Vector((bone.head[0],cursor_local[1],cursor_local[2])) elif angle > 22.5 and angle < 67.5: ### up right bone.tail = (bone.head + Vector((mouse_vec[0],0,mouse_vec[0]))) elif angle > 67.5 and angle < 112.5: ### right bone.tail = Vector((cursor_local[0],cursor_local[1],bone.head[2])) elif angle > 112.5 and angle < 157.5: ### down right bone.tail = (bone.head + Vector((mouse_vec[0],0,-mouse_vec[0]))) elif angle > 157.5 or angle < -157.5: ### down bone.tail = Vector((bone.head[0],cursor_local[1],cursor_local[2])) elif angle > -157.5 and angle < -112.5: ### down left bone.tail = (bone.head + Vector((mouse_vec[0],0,mouse_vec[0]))) elif angle > -112.5 and angle < -67.5: ### left bone.tail = Vector((cursor_local[0],cursor_local[1],bone.head[2])) elif angle > -67.5 and angle < -22.5: ### left up bone.tail = (bone.head + Vector((mouse_vec[0],0,-mouse_vec[0]))) else: bone.tail = cursor_local
def get_bone_angle(armature,bone,relative=True): loc, rot, scale = get_bone_matrix(armature,bone,relative).decompose() compat_euler = Euler((0.0,0.0,math.pi),"XYZ") angle = -rot.to_euler().z # negate angle to fit dragonbones angle return round(math.degrees(angle),2)
def get_mesh(self, bend, base_shape, index): """produce leaf mesh at position of this leaf given base mesh as input""" # calculate angles to transform mesh to align with desired direction trf = self.direction.to_track_quat('Z', 'Y') right_t = self.right.rotated(trf.inverted()) spin_ang = pi - right_t.angle(Vector([1, 0, 0])) # calculate bend transform if needed if bend > 0: bend_trf_1, bend_trf_2 = self.calc_bend_trf(bend) else: bend_trf_1 = bend_trf_2 = None vertices = [] for vertex in base_shape[0]: # rotate to correct direction vertex = vertex.copy() vertex.rotate(Quaternion(Vector([0, 0, 1]), spin_ang)) vertex.rotate(trf) # apply bend if needed if bend > 0: vertex.rotate(bend_trf_1) vertex.rotate(bend_trf_2) # move to right position vertex += self.position # add to vertex array vertices.append(vertex) # set face to refer to vertices at correct offset in big vertex list index *= len(vertices) faces = deepcopy(base_shape[1]) for face in faces: for ind, elem in enumerate(face): face[ind] = elem + index return vertices, faces
def calc_bend_trf(self, bend): """calculate the transformations required to 'bend' the leaf out/up from WP""" normal = self.direction.cross(self.right) theta_pos = atan2(self.position.y, self.position.x) theta_bend = theta_pos - atan2(normal.y, normal.x) bend_trf_1 = Quaternion(Vector([0, 0, 1]), theta_bend * bend) self.direction.rotate(bend_trf_1) self.right.rotate(bend_trf_1) normal = self.direction.cross(self.right) phi_bend = normal.declination() if phi_bend > pi / 2: phi_bend = phi_bend - pi bend_trf_2 = Quaternion(self.right, phi_bend * bend) return bend_trf_1, bend_trf_2
def calc_helix_points(turtle, rad, pitch): """ calculates required points to produce helix bezier curve with given radius and pitch in direction of turtle""" # alpha = radians(90) # pit = pitch/(2*pi) # a_x = rad*cos(alpha) # a_y = rad*sin(alpha) # a = pit*alpha*(rad - a_x)*(3*rad - a_x)/(a_y*(4*rad - a_x)*tan(alpha)) # b_0 = Vector([a_x, -a_y, -alpha*pit]) # b_1 = Vector([(4*rad - a_x)/3, -(rad - a_x)*(3*rad - a_x)/(3*a_y), -a]) # b_2 = Vector([(4*rad - a_x)/3, (rad - a_x)*(3*rad - a_x)/(3*a_y), a]) # b_3 = Vector([a_x, a_y, alpha*pit]) # axis = Vector([0, 0, 1]) # simplifies greatly for case inc_angle = 90 points = [Vector([0, -rad, -pitch / 4]), Vector([(4 * rad) / 3, -rad, 0]), Vector([(4 * rad) / 3, rad, 0]), Vector([0, rad, pitch / 4])] # align helix points to turtle direction and randomize rotation around axis trf = turtle.dir.to_track_quat('Z', 'Y') spin_ang = rand_in_range(0, 2 * pi) for p in points: p.rotate(Quaternion(Vector([0, 0, 1]), spin_ang)) p.rotate(trf) return points[1] - points[0], points[2] - points[0], points[3] - points[0], turtle.dir.copy()
def points_for_floor_split(self): """Calculate Poissonly distributed points for stem start points""" array = [] # calculate approx spacing radius for dummy stem self.tree_scale = self.param.g_scale + self.param.g_scale_v stem = Stem(0, None) stem.length = self.calc_stem_length(stem) rad = 2.5 * self.calc_stem_radius(stem) # generate points for _ in range(self.param.floor_splits + 1): point_ok = False while not point_ok: # distance from center proportional for number of splits, tree scale and stem radius dis = sqrt(rand_in_range(0, 1) * self.param.floor_splits / 2.5 * self.param.g_scale * self.param.ratio) # angle random in circle theta = rand_in_range(0, 2 * pi) pos = Vector([dis * cos(theta), dis * sin(theta), 0]) # test point against those already in array to ensure it will not intersect point_m_ok = True for point in array: if (point[0] - pos).magnitude < rad: point_m_ok = False break if point_m_ok: point_ok = True array.append((pos, theta)) return array
def shape_ratio(self, shape, ratio): """Calculate shape ratio as defined in paper""" if shape == 1: # spherical result = 0.2 + 0.8 * sin(pi * ratio) elif shape == 2: # hemispherical result = 0.2 + 0.8 * sin(0.5 * pi * ratio) elif shape == 3: # cylindrical result = 1.0 elif shape == 4: # tapered cylindrical result = 0.5 + 0.5 * ratio elif shape == 5: # flame if ratio <= 0.7: result = ratio / 0.7 else: result = (1.0 - ratio) / 0.3 elif shape == 6: # inverse conical result = 1.0 - 0.8 * ratio elif shape == 7: # tend flame if ratio <= 0.7: result = 0.5 + 0.5 * ratio / 0.7 else: result = 0.5 + 0.5 * (1.0 - ratio) / 0.3 elif shape == 8: # envelope if ratio < 0 or ratio > 1: result = 0.0 elif ratio < 1 - self.param.prune_width_peak: result = pow(ratio / (1 - self.param.prune_width_peak), self.param.prune_power_high) else: result = pow((1 - ratio) / (1 - self.param.prune_width_peak), self.param.prune_power_low) else: # conical (0) result = 0.2 + 0.8 * ratio return result
def get_border_cell(s2_id): locs = [] s2_cell = Cell(s2_id) for i in [0, 1]: for j in [0, 1]: locs.append([s2_cell.get_latitude(i, j) * 180 / pi, s2_cell.get_longitude(i, j) * 180 / pi]) output = [locs[0], locs[1], locs[3], locs[2], locs[0]] return output
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
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
def degrees(radians): return 180 * (radians / math.pi)