Beispiel #1
0
    def attack(self, x, y, direction, targets, inventory):
        if self.ammo in inventory and inventory[self.ammo] > 0:
            shots = []
            for i in xrange(self.burst):
                slope = math.tan(random.uniform(float(direction) - self.spread, float(direction) + self.spread))
                shot = item.GunShot(x, y, slope)
                messenger.Messenger.addItem(shot)
                shots.append(shot)
            if inventory[self.ammo]:
                inventory[self.ammo] -= self.burst
                for target in targets:
                    distance = math.sqrt(float(target.y - y) ** 2 + (target.x - x) ** 2)
                    slope = (target.y - y) / (target.x - x)
                    if distance <= self.distance + target.size:
                        for shot in shots:
                            messenger.Messenger.addItem(shot)
                            if (
                                math.atan(slope) - self.spread
                                < math.atan(shot.slope)
                                < math.atan(slope.slope) + self.spread
                            ):
                                target.health -= damage

            else:
                pass
Beispiel #2
0
def  inverseDepth(u,v,q_r,q_i,q_j,q_k,x,y,z):
    """returns the inverse depth parameters [theta, phi,rho] for the feature point specified by pixel coordinates (u,v), 
       camera pose described by unit quaternion (q_r,q_i,q_j,q_k) and camera 3D location specified by [x,y,z]
        
        Keyword arguments:
        u - pixel coordinate of the feature (u)
        v - pixel coordinate of the feature (v)
        q_r - real component of the unit quaternion
        q_i - component of unit quaternion along i-axis
        q_j - component of unit quaternion along j-axis
        q_k - component of unit quaternion along k-axis
        x - position of camera w.r.t world reference frame
        y - position of camera w.r.t world reference frame
        z - position of camera w.r.t world reference frame
        
    """
    
    q2r = get_q2r(q_r,q_i,q_j,q_k)      #generating the r_CW, for transforming the quaternion from world coordinate to camera coordinate
                    
    hw_ = np.array([[((param.Cu - u)*(param.Fu))],[((param.Cv - v)*(param.Fv))],[1]])  # there is some ambiguity with the concept of Fu and Fv. we are supposed to use (f/du) and (f/dv) here. not sure if these are same!
    hw = np.dot(q2r,hw_)
    
    inverseDepth = np.array([[math.atan(hw[0]/hw[1])], #inverse depth estimation
                             [math.atan((-hw[1])/(math.sqrt((hw[0])**2 + (hw[2])**2)))],
                             [param.INITIAL_DEPTH_ESTIMATE]])
                    
    return inverseDepth
Beispiel #3
0
def paint_canvas(x, y, colors):
	"""creates the png file and colors colors it
	"""
	sys.setrecursionlimit(15000)
	padding = 1
	point1hat = math.atan((y[3] - y[0])/(x[3] - x[0])) + math.pi

	if x[75] - x[0] < 0:
		point1hat = math.pi + point1hat
	point2hat = math.atan((y[-1] - y[-3])/(x[-1] - x[-3]))
	if x[-1] - x[-75] < 0:
		point2hat = math.pi + point2hat

	closeIt = bezier((x[0],y[0]), point1hat, (x[-1],y[-1]), point2hat)	#calls bezier function in order to close the open loop
	xnew = x + closeIt[0]
	ynew = y + closeIt[1]

	canvas = Image.new("RGB",(int(round(max(xnew)- min(xnew)))+2*padding, int(round((max(ynew) - min(ynew))))+2*padding))
	pixels = canvas.load()

	for i in range(len(xnew)):
		pixels[xnew[i]+padding+0, ynew[i]+padding+0] = (255, 255, 255)

	imagepath = "images/techtest.png"
	canvas.save(imagepath)
	centers = findZones(imagepath)

	for i in range(len(centers)):
		flood(pixels,centers[i], color = colors[i%len(colors)], visited = [])

	canvas = canvas.resize((1000,1000), Image.NEAREST)
	canvas.save(imagepath)	
Beispiel #4
0
def fromwgs84(lat, lng, pkm=False):
    """
    Convert coordintes from WGS84 to TWD97

    pkm true for Penghu, Kinmen and Matsu area
    The latitude and longitude can be in the following formats:
        [+/-]DDD°MMM'SSS.SSSS" (unicode)
        [+/-]DDD°MMM.MMMM' (unicode)
        [+/-]DDD.DDDDD (string, unicode or float)
    The returned coordinates are in meters
    """

    _lng0 = lng0pkm if pkm else lng0

    lat = radians(todegdec(lat))
    lng = radians(todegdec(lng))

    t = sinh((atanh(sin(lat)) - 2*pow(n,0.5)/(1+n)*atanh(2*pow(n,0.5)/(1+n)*sin(lat))))
    epsilonp = atan(t/cos(lng-_lng0))
    etap = atan(sin(lng-_lng0) / pow(1+t*t, 0.5))

    E = E0 + k0*A*(etap + alpha1*cos(2*1*epsilonp)*sinh(2*1*etap) + 
                          alpha2*cos(2*2*epsilonp)*sinh(2*2*etap) +
                          alpha3*cos(2*3*epsilonp)*sinh(2*3*etap))
    N = N0 + k0*A*(epsilonp + alpha1*sin(2*1*epsilonp)*cosh(2*1*etap) +
                              alpha2*sin(2*2*epsilonp)*cosh(2*2*etap) +
                              alpha3*sin(2*3*epsilonp)*cosh(2*3*etap))

    return E*1000, N*1000
Beispiel #5
0
	def execute(self, context):
		lightOffset = 20
		lightHeight = 20
		scene = context.scene
		# delete active object if it is a mesh
		active = context.object
		if active and active.type=="MESH":
			bpy.ops.object.delete()
		# getting width and height of the footprint
		w, h = [float(i) for i in self.size.split("x")]
		# add lights
		rx = math.atan((h+lightOffset)/lightHeight)
		rz = math.atan((w+lightOffset)/(h+lightOffset))
		def lamp_add(x, y, rx, rz):
			bpy.ops.object.light_add(
				type="SUN",
				location=((x,y,lightHeight)),
				rotation=(rx, 0, rz)
			)
			context.active_object.data.energy = 0.5
		lamp_add(w+lightOffset, h+lightOffset, -rx, -rz)
		lamp_add(-w-lightOffset, h+lightOffset, -rx, rz)
		lamp_add(-w-lightOffset, -h-lightOffset, rx, -rz)
		lamp_add(w+lightOffset, -h-lightOffset, rx, rz)
		
		create_rectangle(context, w, h)
		align_view(context.object)
		
		return {"FINISHED"}
    def _ctrl_steering(self, steer_ang, steer_ang_vel_limit, delta_t):
        # Control the steering joints.

        # Compute theta, the virtual front wheel's desired steering angle.
        if steer_ang_vel_limit > 0.0:
            # Limit the steering velocity.
            ang_vel = (steer_ang - self._last_steer_ang) / delta_t
            ang_vel = max(-steer_ang_vel_limit,
                           min(ang_vel, steer_ang_vel_limit))
            theta = self._last_steer_ang + ang_vel * delta_t
        else:
            theta = steer_ang

        # Compute the desired steering angles for the left and right front
        # wheels.
        center_y = self._wheelbase * math.tan((pi / 2) - theta)
        steer_ang_changed = theta != self._last_steer_ang
        if steer_ang_changed:
            self._last_steer_ang = theta
            self._theta_left = \
                _get_steer_ang(math.atan(self._inv_wheelbase *
                                         (center_y - self._joint_dist_div_2)))
            self._theta_right = \
                _get_steer_ang(math.atan(self._inv_wheelbase *
                                         (center_y + self._joint_dist_div_2)))

        return steer_ang_changed, center_y
Beispiel #7
0
   def wmplugin_exec(self, m):
	
	axes = [None, None, None, None]


	self.acc = [self.NEW_AMOUNT*(new-zero)/(one-zero) + self.OLD_AMOUNT*old
	       for old,new,zero,one in zip(self.acc,m,self.acc_zero,self.acc_one)]
	a = math.sqrt(sum(map(lambda x: x**2, self.acc)))

	roll = math.atan(self.acc[cwiid.X]/self.acc[cwiid.Z])
	if self.acc[cwiid.Z] <= 0:
		if self.acc[cwiid.X] > 0: roll += math.pi
		else: roll -= math.pi

	pitch = math.atan(self.acc[cwiid.Y]/self.acc[cwiid.Z]*math.cos(roll))

	axes[0] = int(roll  * 1000 * self.Roll_Scale)
	axes[1] = int(pitch * 1000 * self.Pitch_Scale)

	if (a > 0.85) and (a < 1.15):
		if (math.fabs(roll)*(180/math.pi) > 10) and \
		   (math.fabs(pitch)*(180/math.pi) < 80):
			axes[2] = int(roll * 5 * self.X_Scale)

		if (math.fabs(pitch)*(180/math.pi) > 10):
			axes[3] = int(pitch * 10 * self.Y_Scale)

	return math.degrees(pitch), math.degrees(roll)
 def arctan(x, y):
     if x > 0:
         return math.atan(-y/x)
     elif x < 0:
         return math.pi - math.atan(y/x)
     else: #x is 0
         return math.copysign(math.pi/2, -y)
Beispiel #9
0
 def gazePix(self,anglex,angley):
     """Converts gaze angle to monitor pixel"""
     alphax = math.degrees(math.atan(self.ledx/self.monitordistance))
     pixx = self.deg2pix(anglex-alphax)
     alphay = math.degrees(math.atan(self.ledy/self.monitordistance))
     pixy = self.deg2pix(angley-alphay)
     return pixx,pixy
def correct_rgc(coord, glx_ctr=ICRS('00h42m44.33s +41d16m07.5s'), glx_PA=Angle('37d42m54s'), glx_incl=Angle('77.5d'), glx_dist=Distance(783,unit=u.kpc)):
    '''computes deprojected galactocentric distance for an object at coord,
       relative to galaxy at glx_ctr with PA glx_PA, inclination glx_incl, distance glx_distance'''

    # distance from coord to glx centre
    sky_radius = glx_ctr.separation(coord)
    avg_dec = 0.5*(glx_ctr.dec + coord.dec).radian
    x = (glx_ctr.ra - coord.ra)*mt.cos(avg_dec)
    y = glx_ctr.dec - coord.dec
    # azimuthal angle from coord to glx  -- not completely happy with this
    phi = glx_PA - Angle('90d') + Angle(mt.atan(y.arcsec/x.arcsec),unit=u.rad) 

    # convert to coordinates in rotated frame, where y-axis is galaxy major axis
    # have to convert to arcmin b/c can't do sqrt(x^2+y^2) when x and y are angles
    xp = (sky_radius * mt.cos(phi.radian)).arcmin
    yp = (sky_radius * mt.sin(phi.radian)).arcmin

    # de-project
    ypp = yp/mt.cos(glx_incl.radian)
    obj_radius = mt.sqrt(xp**2+ypp**2) # in arcmin
    obj_dist = Distance(Angle(obj_radius, unit=u.arcmin).radian*glx_dist,unit=glx_dist.unit)

    # don't really need this but compute it just for fun
    if abs(Angle(xp,unit=u.arcmin))<Angle(1e-5,unit=u.rad):
        obj_phi = Angle(0.0)
    else:
        obj_phi = Angle(mt.atan(ypp/xp),unit=u.rad)
    return(obj_dist)
Beispiel #11
0
    def lift_drag(self, state_vector, t, vec = [-1, 0, 1]):
        """
        vec = [-1, 0, 1]
        Drag versor in capsule coordinate system
        """
        x, y, vx, vy = state_vector

        # kąt promienia wodzącego
        tau_r = atan(-x/y)

        # Flight Patch Angle
        FPA = atan(vy/vx)

        # convert time to positive numbers
        t = t + self.SUFR_duration_total

        # Bank change time (from charts, approx)
        roll_time = 10          # s

        #~ if t <= roll_time:
            #~ AoA = self.AoA_at_SUFR_start*(1-t*(1./roll_time))
        #~ elif t > roll_time:
            #~ AoA = 0.
        AoA = self.AoA_function(t)*cos(self.bank_function(t))
        # tau_r > 0; FPA < 0, AoA > 0
        # everything should be < 0
        Ex, Ey, __ = np.matrix(vec).dot(self.obrot_o_kat(-tau_r +FPA -AoA)).tolist()[0]
        return Ex, Ey
Beispiel #12
0
	def testEvent(self,timestamp,ID,x,y,z):
		"""tests to see if the current wiimote position needs to trigger an event.
		creates and sends the wii event if needed"""	
		x = -1 * x#flips x acceleration
		if z == 0:#since tangent will be x/z, z = 0 needs to be slightly adjusted to avoid DIVIDE BY 0
			z = .0000000001
		if abs(z) < ParserSettings.ROLL_PITCH_LOCKOUT_THRESHOLD and abs(x) < ParserSettings.ROLL_PITCH_LOCKOUT_THRESHOLD:
			#checks if there may be a roll or pitch occuring, where the accelerometers are spiking.
			#function doesnt test for a roll or pitch event if there is a flick occuring.
			#intent is to prevent false positives with roll and pitch events as much as possible.
			roll = math.atan(float(x)/float(z))#roll is calculated comparing calibrated x and z acceleration values
			pitch = math.atan(float(y)/float(z))*math.cos(roll)#pich is compared with calibrated y and z, modified by the roll
		
			if (roll - self.currentRoll) > ParserSettings.ROLL_THRESHOLD:
				#tests to see if the roll has changed enough to trigger an event
				triggeredEvent = WiiEvent.WiiEvent(ID,'Roll',1,timestamp)
				triggeredEvent.fireEvent()
				self.currentRoll = self.currentRoll + ParserSettings.ROLL_THRESHOLD
			elif(self.currentRoll - roll) > ParserSettings.ROLL_THRESHOLD:
				#tests for roll in other direction
				triggeredEvent = WiiEvent.WiiEvent(ID,'Roll',-1,timestamp)
				triggeredEvent.fireEvent()
				self.currentRoll = self.currentRoll - ParserSettings.ROLL_THRESHOLD
	
			if (pitch - self.currentPitch) > ParserSettings.PITCH_THRESHOLD:
				#tests pitch in same manner as role, relative to standard threshold
				triggeredEvent = WiiEvent.WiiEvent(ID,'Pitch',1,timestamp)
				triggeredEvent.fireEvent()
				self.currentPitch = self.currentPitch + ParserSettings.PITCH_THRESHOLD
			elif(self.currentPitch - pitch) > ParserSettings.PITCH_THRESHOLD:
				#tests other direction of pitch
				triggeredEvent = WiiEvent.WiiEvent(ID,'Pitch',-1,timestamp)
				triggeredEvent.fireEvent()
				self.currentPitch = self.currentPitch - ParserSettings.PITCH_THRESHOLD
def transform(x,y,z):
    initial_angle=math.acos(L/(4*l))#
    bed_angle=math.asin((z-square_z)/l)#
    leg_offset=l*math.cos(bed_angle)
    yprime=y+y_offset-leg_offset
    xprime=x+L/2
    topz=((d/2-y)/d)*front_z+(1-(d/2-y)/d)*back_z
    bed_tilt=math.atan2(-back_z+front_z,d)
    yprime-=z*math.sin(bed_tilt)
    zprime=topz-z*math.cos(bed_tilt)
    left_leg=math.sqrt(xprime*xprime+yprime*yprime)
    right_leg=math.sqrt((L-xprime)*(L-xprime)+yprime*yprime)
    left_elbow=math.acos((left_leg*left_leg-2*l*l)/(-2*l*l))
    right_elbow=math.acos((right_leg*right_leg-2*l*l)/(-2*l*l))
    left_small_angle=(math.pi-left_elbow)/2
    right_small_angle=(math.pi-right_elbow)/2
    left_virtual=math.atan(-yprime/xprime)
    right_virtual=math.atan(-yprime/(L-xprime))
    left_drive=left_small_angle+left_virtual-initial_angle
    right_drive=right_small_angle+right_virtual-initial_angle
    left_stepper=-left_drive+(math.pi-left_elbow)*mechanical_advantage
    right_stepper=-right_drive+(math.pi-right_elbow)*mechanical_advantage
    #print "left_angle: "+str(left_drive)+" left_elbow: "+str(math.pi-left_elbow)
    #print "right_angle: "+str(left_drive)+" right_elbow: "+str(math.pi-right_elbow)
    return left_stepper*200/math.pi,right_stepper*200/math.pi,zprime
Beispiel #14
0
def followCentre(data,desired_trajectory):
	global alpha

	a = getRange(data,130)
	b = getRange(data,179.9)
	swing = math.radians(50)
	print "center distances: ", a, b
	alpha = -math.atan((a*math.cos(swing)-b)/(a*math.sin(swing)))
	print "Alpha left",math.degrees(alpha)
	curr_dist1 = b*math.cos(alpha)
	future_dist1 = curr_dist1-car_length*math.sin(alpha)



	a = getRange(data,50)
	b = getRange(data,0)
	swing = math.radians(50)
	alpha = math.atan((a*math.cos(swing)-b)/(a*math.sin(swing)))
	print "Alpha right",math.degrees(alpha)
	curr_dist2 = b*math.cos(alpha)

	future_dist2 = curr_dist2+car_length*math.sin(alpha)

	desired_trajectory = (future_dist1 + future_dist2)/2

	print "dist 1 : ",future_dist1
	print "dist 2 : ",future_dist2
	# print "dist : ",future_dist
	error = future_dist1 - future_dist2
	print "Error : ",error
	return error, curr_dist2-curr_dist1
    def trouverInfoRobot(self, contourGauche, contourDroit):
        centreGauche = self.trouverCentre(contourGauche)
        centreDroit = self.trouverCentre(contourDroit)
        centreRobot = (int(round((centreDroit[0]+centreGauche[0])/2)), int(round((centreDroit[1]+centreGauche[1])/2)))
        deltaX = centreDroit[0]-centreGauche[0]
        deltaY = -1*(centreDroit[1]-centreGauche[1])
        if not deltaX == 0:
            pente = deltaY/deltaX

        if deltaY == 0 and deltaX < 0:
            angle = 180
        elif deltaY == 0 and deltaX > 0:
            angle = 0
        elif deltaX == 0 and deltaY > 0:
            angle = 90
        elif deltaX == 0 and deltaY < 0:
            angle = 270
        elif deltaX > 0 and deltaY > 0:
            angle = int(round(math.degrees(math.atan(pente))))
        elif deltaX > 0 and deltaY < 0:
            angle = 360 + int(round(math.degrees(math.atan(pente))))
        elif deltaX < 0:
            angle = 180 + int(round(math.degrees(math.atan(pente))))

        angle += 90
        if angle >= 360:
            angle -= 360

        return centreRobot, angle
Beispiel #16
0
def CartesianCoordinatesToPolarCoordinates(x, y):
    """
    convert a tuple that represents a vector in cartesian coordinates to polar coordinates.
    The zero angle of the polar representation corresponds to x-direction of cartesian representation.

    INPUT parameters:
    x: x-value of vector in cartesian coordinates (numeric)
    y: y-value of vector in cartesian coordinates (numeric)

    OUTPUT:
    r:      radial coordinate of vector in polar coordinates (numeric)
    phi:    anglular coordinate of vector in polar coordinates (numeric)[radians]
    """

    r = sqrt(x ** 2 + y ** 2)
    if x > 0.0:  # arctangent is not unique
        phi = atan(y / x)
    elif x < 0.0:
        phi = atan(y / x) + pi * sign(y)
    else:  # absolute value of x/y is infinity
        if y > 0.0:
            phi = pi / 2
        elif y < 0.0:
            phi = -pi / 2
        else:
            phi = 0.0  # this is arbitrary

    return [r, phi]
Beispiel #17
0
def generate_wind(nodes, cells, prevailing_wind_bearing=270, average_wind_speed=7.0):
    import noise
    import math
    import numpy as np
    for n in nodes:
        wind_bearing = (int(round(180.0 * noise.pnoise3(n.x, n.y, n.z))) + 360) % 360  # in degrees
        wind_strength = (8 * noise.pnoise3(n.x, n.y, n.z)) + 16.0  # kmph

        # move the generated random wind bearing towards the prevailing wind a little
        wind_vector = np.add(np.array([wind_strength * math.cos(math.radians(90 - wind_bearing)),
                                       wind_strength * math.cos(math.radians(wind_bearing))]),
                             np.array([average_wind_speed * math.cos(math.radians(90 - prevailing_wind_bearing)),
                                       average_wind_speed * math.cos(math.radians(prevailing_wind_bearing))]))

        wind_strength = math.sqrt(math.pow(wind_vector[0], 2) + math.pow(wind_vector[1], 2)) #  sqrt((x2-x1)^2 + (y2-y1)^2) = vector magnitude
        wind_bearing = int(round(math.degrees(math.atan(wind_vector[1]/wind_vector[0])))) # tan-1((y2-y1)/x2-x1)) = vector bearing

        n.set_feature(['wind', 'bearing'], wind_bearing)
        n.set_feature(['wind', 'strength'], wind_strength)
        n.set_feature(['wind', 'vector', 'x'], wind_vector[0])
        n.set_feature(['wind', 'vector', 'y'], wind_vector[1])
        n.wind = Wind(wind_bearing, wind_strength, wind_vector)
    for c in cells:
        wind_vector = np.sum(np.array([n.wind.vector for n in c.nodes]), axis=0)
        wind_strength = math.sqrt(math.pow(wind_vector[0], 2) + math.pow(wind_vector[1], 2))  #  sqrt((x2-x1)^2 + (y2-y1)^2) = vector magnitude
        wind_bearing = int(round(math.degrees(math.atan(wind_vector[1]/wind_vector[0]))))  # tan-1((y2-y1)/x2-x1)) = vector bearing

        c.wind = Wind(wind_bearing, wind_strength, wind_vector)
Beispiel #18
0
	def iterateRegio(self, pl, rwa, rwd, robl, rpoh, lon):
		
		okGa = okGd = True

		if pl.speculums[0][Planet.PMP] < 90.0 or (pl.speculums[0][Planet.PMP] >= 270.0 and pl.speculums[0][Planet.PMP] < 360.0):
			Ga = math.degrees(math.cos(rwa)*math.cos(robl)-math.sin(robl)*math.tan(rpoh))
			if Ga != 0.0:
				Fa = math.degrees(math.atan(math.sin(rwa)/(math.cos(rwa)*math.cos(robl)-math.sin(robl)*math.tan(rpoh))))

				if Fa >= 0.0 and Ga > 0.0:
					lon = Fa
				elif Fa < 0.0 and Ga > 0.0:
					lon = Fa+360.0
				elif Ga < 0.0:
					lon = Fa+180.0
			else:
				okGa = False
		else:
			Gd = math.degrees(math.cos(rwd)*math.cos(robl)+math.sin(robl)*math.tan(rpoh))
			if Gd != 0.0:
				Fd = math.degrees(math.atan(math.sin(rwd)/(math.cos(rwd)*math.cos(robl)+math.sin(robl)*math.tan(rpoh))))

				if Fd >= 0.0 and Gd > 0.0:
					lon = Fd
				elif Fd < 0.0 and Gd > 0.0:
					lon = Fd+360.0
				elif Gd < 0.0:
					lon = Fd+180.0
			else:
				okGd = False

		return okGa, okGd, lon
Beispiel #19
0
def get_vector_angle(pt1, pt2):
    """Retourne l'angle d'une barre par rapport à l'axe X
    compris entre -pi et pi"""
    x1, y1 = pt1
    x2, y2 = pt2[0:2] # revoir à cause des chargements ponctuels
    return math.atan2(y2-y1, x2-x1)



    if x2 == x1:
      if y1 == y2:
        return None
      if y2 > y1:
        return math.pi/2 
      return -math.pi/2
    if y2 == y1:
      if x1 == x2:
        return None
      if x2 >= x1:
        return 0.
      return math.pi
    if y2-y1 <= 0 and x2-x1 <= 0 :
      return math.atan((y2-y1)/(x2-x1)) - math.pi
    if y2-y1>0 and x2-x1 <= 0:
      return math.atan((y2-y1)/(x2-x1)) + math.pi
    return math.atan((y2-y1)/(x2-x1))
Beispiel #20
0
def cal_angle(x_next,x_curr,y_next,y_curr,x_hori,y_vert,northAt):
  # 1st Quadrant
  if x_next > x_curr and y_next > y_curr:
    angle = (90 - math.degrees(math.atan(y_vert/x_hori)))
  # 2nd Quadrant
  elif x_next > x_curr and y_next < y_curr:
    angle = math.degrees(math.atan(y_vert/x_hori)) + 90
  # 3rd Quadrant
  elif x_next < x_curr and y_next < y_curr:
    angle = 270 - math.degrees(math.atan(y_vert/x_hori))
  # 4th Quadrant
  elif x_next < x_curr and y_next > y_curr:
    angle = math.degrees(math.atan(y_vert/x_hori)) + 270
  elif x_next == x_curr and y_next > y_curr:
    angle = 0
  elif x_next == x_curr and y_next < y_curr:
    angle = 180
  elif x_next > x_curr and y_next == y_curr:
    angle = 90
  elif x_next < x_curr and y_next == y_curr:
    angle = 270    

  angle = angle - northAt
  
  if angle >= 360:
      angle -= 360
  elif angle < 0:
    angle += 360

  return angle    
Beispiel #21
0
	def getZD(self, md, lat, decl, umd):
		'''Calculates Regiomontan zenith distance '''

		zd = 0.0
		if md == 90.0:
			zd = 90.0-math.degrees(math.atan(math.sin(math.fabs(math.radians(lat))))*math.tan(math.radians(decl)))
		elif md < 90.0:
			A = math.degrees(math.atan(math.cos(math.radians(lat))*math.tan(math.radians(md))))
			B = math.degrees(math.atan(math.tan(math.fabs(math.radians(lat)))*math.cos(math.radians(md))))

			C = 0.0
			if (decl < 0 and lat < 0) or (decl >= 0 and lat >= 0):
				if umd:
					C = B-math.fabs(decl)
				else:
					C = B+math.fabs(decl)
			elif (decl < 0 and lat > 0) or (decl > 0 and lat < 0):
				if umd:
					C = B+math.fabs(decl)
				else:
					C = B-math.fabs(decl)

			F = math.degrees(math.atan(math.sin(math.fabs(math.radians(lat)))*math.sin(math.radians(md))*math.tan(math.radians(C)))) #C and F can be negative
			zd = A+F

		return zd
Beispiel #22
0
    def TurnToBall(self):
        self.brain.output.printf("TurnToBall")
        if self.brain.ball.confidence > 0:
            if self.gcData.Tcolor() == Constants.TEAM.RED:
                alpha = self.R_Theta - atan((self.B_Y - self.R_Y)/(self.B_X - self.R_X))
                if abs(alpha) > self.turnDeg:#self.turnDeg is the minimum degree that needs to turn
                    if alpha < 2*pi - alpha:
                        turnCCW = -alpha * sin(alpha)
                        self.brain.setWalk(1,0,0,turnCCW)
                    else:
                        turnCCW = (2*pi - alpha)*sin(2*pi - alpha)
                        self.brain.setWalk(1,0,0,turnCCW)

            else:
                alpha = pi - self.R_Theta -atan((self.B_Y - self.R_Y)/(self.R_X - self.R_X - self.B_X))
                if abs(alpha) >self.turnDeg:
                    if alpha <2*pi - alpha:
                        turnCCW = alpha * sin(alpha)
                        self.brain.setWalk(1,0,0,turnCCW)
                    else:
                        turnCCW = -alpha*sin(-alpha)
                        self.brain.setWalk(1,0,0,turnCCW)

        else:
            FindBall(self.brain)
Beispiel #23
0
def mu_2_1(ay, by):
    return (1.0 / (2.0 * by)) * \
            (2.0 * ay * \
                    (atan((1.0 - ay) / by) + atan((1.0 + ay) / by)) + \
              by * \
                    (log((-1.0 + ay) ** 2 + by ** 2) - \
                     log((1.0 + ay) ** 2 + by ** 2)))
Beispiel #24
0
def Meter2px(h,vd,vd1,hd,nrows,ncols):
    ### real scale (unit : meter)
    #h  : building size
    #vd : distance between buliding to the bottom of the image
    #vd1: distance between bottom to up of the image
    #hd : horizontal distancd
    
    ### pixels based
    # nrows
    # ncols


    theta = math.atan(1.*vd/h) #radius 
    z=(h**2+vd**2)**0.5
    alpha = pi/2-theta
    beta = math.atan((vd+vd1)*1./h)-theta

    ydp = beta/ncols
    xdp = beta/nrows

    ylen = np.zeros(ncols)
    xlen = np.ones(nrows)*hd/nrows

    distance = vd
    for i in range(ncols):
        
        gamma = (theta+ydp*(1+i))
        pylen = h*math.tan(gamma)-distance # pixel length
        ylen[i] = pylen
        distance = distance+pylen

    print ylen[-1]/ylen[0]
    return xlen,ylen[::-1]
Beispiel #25
0
def mu_6_0(ay, by):
    return ((-3.0 * (-1.0 + ay)**3.0 * by - 5.0 * (-1.0 + ay) * by**3.0)/\
            ((-1.0 + ay)**2.0 + by**2.0)**2.0 + \
            (3.0 * (1.0 + ay)**3.0 * by + 5.0 * (1.0 + ay) * by ** 3.0)/\
            ((1.0 + ay)**2.0 + by**2.0)**2.0 -
            3.0 * atan((-1.0 + ay)/by) + 3.0 * atan((1.0 + ay)/by))/\
                    (8.0 * by**5.0)
Beispiel #26
0
    def __init__(self, central_longitude=0.0, satellite_height=35785831,
                 false_easting=0, false_northing=0, globe=None):
        proj4_params = [('proj', 'geos'), ('lon_0', central_longitude),
                        ('lat_0', 0), ('h', satellite_height),
                        ('x_0', false_easting), ('y_0', false_northing),
                        ('units', 'm')]
        super(Geostationary, self).__init__(proj4_params, globe=globe)

        # TODO: Factor this out, particularly if there are other places using
        # it (currently: Stereographic & Geostationary). (#340)
        def ellipse(semimajor=2, semiminor=1, easting=0, northing=0, n=200):
            t = np.linspace(0, 2 * np.pi, n)
            coords = np.vstack([semimajor * np.cos(t), semiminor * np.sin(t)])
            coords += ([easting], [northing])
            return coords

        # TODO: Let the globe return the semimajor axis always.
        a = np.float(self.globe.semimajor_axis or 6378137.0)
        b = np.float(self.globe.semiminor_axis or 6378137.0)
        h = np.float(satellite_height)
        max_x = h * math.atan(a / (a + h))
        max_y = h * math.atan(b / (b + h))

        coords = ellipse(max_x, max_y,
                         false_easting, false_northing, 60)
        coords = tuple(tuple(pair) for pair in coords.T)
        self._boundary = sgeom.polygon.LinearRing(coords)
        self._xlim = self._boundary.bounds[::2]
        self._ylim = self._boundary.bounds[1::2]
        self._threshold = np.diff(self._xlim)[0] * 0.02
def m2nu(m):
    if m < 1:
        raise ValueError('Mach number should be greater than or equal to 1')
    a = (GAMMA+1) / (GAMMA-1)
    b = m**2 - 1
    c = a**-1 * b
    return sqrt(a) * atan(sqrt(c)) - atan(sqrt(b))
Beispiel #28
0
 def GoToPoint(self):
     self.brain.output.printf("go to point")
     PointY = self.B_Y + self.B_Y * (self.B_X - self.X_M)/(self.B_X - self.F_X)
     deltaX = self.R_X - self.X_M
     deltaY = abs(PointY - self.R_Y)
     deltaTheta = R_Theta - (pi - atan(deltaY/deltaX)) 
     dist = sqrt(deltaY * deltaY + deltaX * deltaX)
     forward = 0
     left = 0
     turnCCW = 0
     if dist > self.Radius:
         if R_Theta < pi - atan((deltaY + self.Radius)/deltaX):
             turnCCW = deltaTheta * sin(deltaTheta)#turnCCW=CLIP(deltaTheta,DEG_TO_RAD(-20),DEG_TO_RAD(20))
             self.brain.output.printf2('GoToPoint------turnCCW:::::::',turnCCW)
             self.brain.setWalk(1,0,0,turnCCW)
         elif R_Theta > pi - atan((deltaY - self.Radius)/deltaX):
             turnCCW = -deltaTheta * sin(deltaTheta)#rurnCCW=CLIP(-deltaTheta,DEG_TO_RAD(-20),DEG_TO_RAD(20))
             self.brain.output.printf2('GoToPoint------turnCCW:::::::',turnCCW)
             self.brain.setWalk(1,0,0,turnCCW)
         else:
             self.brain.setWalk(1,0,0,0)
         forward = dist * sin(dist)#or forward = 0.02 can be adopt
         left = dist * sin(dist)#or left = 0.02 can be adopt
         turnCCW = 0
         self.brain.setWalk(1,forward,left,turnCCW)
Beispiel #29
0
def get_vec_ang(vec):
	'''
	Get the angle of a vector in [0,360).
	Input: a 2D vector
	Output: [0, 360)
	'''
	if (0 == vec[0]): # vx = 0
		if (vec[1] > 0):
			return 90
		elif (vec[1] < 0):
			return 270
		else:
			return 0
	else: # vx != 0
		if(0 == vec[1]): # vy = 0
			if(vec[0] > 0):
				return 0
			else:
				return 180
		else: # vx != 0, vy != 0
			temp = math.fabs(vec[1]/vec[0])
			if ( vec[0]>0 and vec[1]>0 ): # 1st quadrant 
				return math.atan(temp) * 180 / math.pi
			elif ( vec[0]<0 and vec[1]>0 ): # 2
				return (math.pi-math.atan(temp)) * 180 / math.pi
			elif ( vec[0]<0 and vec[1]<0 ): # 3
				return (math.pi+math.atan(temp)) * 180 / math.pi
			else: # 4
				return (2*math.pi-math.atan(temp)) * 180 / math.pi
Beispiel #30
0
 def getInfo(self):
     """
     Return the data retrieved from the wiimote properly formatted and ordered
     """
     state = self.wm.state
     (xi, yi, zi), ir_src, buttons = state['acc'], state['ir_src'], state['buttons']
     
     x = float(xi)
     y = float(yi)
     z = float(zi)
     
     #Weight the accelerations according to calibration data and
     #center around 0
     a_x = (x - self._accel_calib[0])/(self._accel_calib[4]-self._accel_calib[0])
     a_y = (y - self._accel_calib[1])/(self._accel_calib[5]-self._accel_calib[1])
     a_z = (z - self._accel_calib[2])/(self._accel_calib[6]-self._accel_calib[2])
     
     try:
         roll = math.atan(float(a_x)/float(a_z))
         if a_z<=0:
                 if (a_x>0):
                         roll -= math.pi
                 else:
                         roll += math.pi
         roll = -roll
         pitch = math.atan(a_y/a_z*math.cos(roll))
         accel = math.sqrt(math.pow(a_x,2)+math.pow(a_y,2)+math.pow(a_z,2))
     
         return pitch, roll, accel, (a_x, a_y, a_z), ir_src, buttons 
     except ZeroDivisionError:
         return 0,0,0,(0,0,0), 0, 0
Beispiel #31
0
from math import atan

from svgfig import *

from fglib import vec
from fglib.util_functional import *

def radial(fig, n):
    return Fig(*map(lambda i: Fig(fig, trans=rotate(360 / float(n) * i, 0, 0)), range(n)))

def perturbFig(fig, px, py):
    return Fig(fig, trans = lambda x, y: (x + px, y + py))

def rotateFigOrient(fig, (x, y)):
    xx, yy = vec.norm((x, y))
    return Fig(fig, trans=rotate(180.0 * atan(yy / xx), 0, 0))

def drawRect(x1, y1, x2, y2):
    return Fig(Rect(x1, y1, x2, y2))

FM = lambda f, xs: Fig(*map(f, xs))

# rows: list of row widths, relative
# cols: list of col heights, relative

def drawGridLines(xstart, ystart, width, height, rows, cols):
    rows_n = map(lambda x: -x, list(vec.scale(tuple(normalize(rows)) , height)))
    cols_n = list(vec.scale(tuple(normalize(cols)) , width))

    ys = scanl(lambda x, y: x + y, [0.0] + rows_n)
    xs = scanl(lambda x, y: x + y, [0.0] + cols_n)
Beispiel #32
0
# prob3: TurtleGraphicsAngles
import math
import turtle
print('Provide two points A and B, get acute angle OAB where O is (0, 0)')
x1 = float(input('enter x-coordinate of first point: '))
y1 = float(input('enter y-coordinate of first point: '))
x2 = float(input('enter x-coordinate of second point: '))
y2 = float(input('enter y-coordinate of second point: '))

if x1 == x2:
    theta = 0
else:
    m1 = y1 / x1
    m2 = (y2 - y1) / (x2 - x1)
    x = abs(m1 - m2)
    if m1 * m2 == -1:
        theta = 90
    else:
        theta = math.atan(x / (1 + m1 * m2)) * 180 / math.pi
print(theta, ' degrees')
print(dir(turtle))
turtle.goto(0, 0)
turtle.pendown()
turtle.goto(x1, y1)
turtle.goto(x2, y2)
turtle.done()
Beispiel #33
0
    def update_author_coauthor(self):
        self.update_author_coauthor_1()
        auth_cursor = self.connection.cursor()
        auth_sql = "SELECT author_id,field FROM new_AuthorFieldData;"
        auth_cursor.execute(auth_sql)
        auth_name = auth_cursor.fetchall()

        for i in range(len(auth_name)):
            core_name = auth_name[i][0]
            core_field = auth_name[i][1]

            # print "Updating "+ core_name
            if (i % 1000 == 0):
                self.connection.commit()


#                 print "##############################################"
#                 print "layer 2 %.2f" % (100 * float(i) / len(auth_name)) + "%updated"
#                 print "##############################################"

# search for layer 1
            co_cursor = self.connection.cursor()
            co_sql = '''SELECT id1,id2,publish_year,cnt FROM new_CoauthorFieldCntYear 
                          WHERE ((id1 = "%s" OR id2 = "%s") AND field = "%s");
                          ''' % (core_name, core_name, core_field)
            co_cursor.execute(co_sql)
            co_name = co_cursor.fetchall()

            expsum = 0.0
            countsum = 0.0

            # calculate for core
            for j in range(len(co_name)):
                layer_co_year = int(co_name[j][2])
                if (layer_co_year < self.start_year
                        or layer_co_year > self.end_year):
                    continue

                if (co_name[j][0] == core_name):
                    layer_name = co_name[j][1]
                else:
                    layer_name = co_name[j][0]

                layer_co_cnt = int(co_name[j][3])

                # search for layer 1 value
                layer_cursor = self.connection.cursor()
                layer_sql = """SELECT coauthor_factor_1,h_index FROM new_AuthorFieldData
                              WHERE author_id = "%s" AND field = "%s";""" % (
                    layer_name, core_field)
                layer_cursor.execute(layer_sql)
                temp = layer_cursor.fetchall()
                if (temp):
                    layer_1_score = float(temp[0][0])
                    layer_1_hinex = float(temp[0][1])
                else:
                    continue

                expsum += layer_co_cnt * e**(atan(layer_1_hinex))
                countsum += layer_co_cnt * e**(atan(layer_1_hinex))
            if (expsum != 0):
                layer_2_score = countsum / expsum
            else:
                layer_2_score = 0.0
            # print "final score: "+ str(layer_2_score)
            # outfile.write("%s %s %f\n" % (core_name, core_field, layer_2_score))
            update_cursor = self.connection.cursor()
            update_sql = '''UPDATE new_AuthorFieldData
                            SET coauthor_factor = %f
                            WHERE author_id = "%s" AND field = "%s";''' % (
                layer_2_score, core_name, core_field)
            update_cursor.execute(update_sql)
        self.connection.commit()
Beispiel #34
0
    def update_author_coauthor_1(self):
        # create view for the first time
        # view_cursor = self.connection.cursor()
        # view_sql = """CREATE VIEW Paper_Author_Year AS
        #     (SELECT * FROM (
        #         (SELECT paper_id,author_id FROM new_PaperAuthor) s1
        #             NATURAL JOIN
        #         ((SELECT paper_id,publish_year FROM new_PaperData) s2
        #             NATURAL JOIN
        #             (SELECT paper_id,field FROM new_PaperFieldData) s3)
        #     ));"""
        #
        # view_cursor.execute(view_sql)
        # view_sql = '''CREATE VIEW Coauthor_paper_year AS(
        #               SELECT id1,id2,s1.paper_id,s1.publish_year,s1.field FROM
        #                 (SELECT author_id as id1,paper_id,publish_year,field FROM Paper_Author_Year) s1
        #               JOIN
        #                 (SELECT author_id as id2,paper_id from Paper_Author_Year) s2
        #               ON id1>id2 AND s1.paper_id = s2.paper_id
        #             )ORDER BY id1;'''
        # view_cursor.execute(view_sql)
        #
        # view_sql = '''CREATE VIEW new_CoauthorFieldCntYear AS(
        #                 SELECT id1,id2,publish_year,field,COUNT(paper_id) FROM
        #                   (SELECT * FROM Coauthor_paper_year ) s1
        #                 GROUP BY id1,id2,field,publish_year
        #             );'''
        # view_cursor.execute(view_sql)

        auth_cursor = self.connection.cursor()
        auth_sql = "SELECT author_id,field,citation FROM new_AuthorFieldData;"
        auth_cursor.execute(auth_sql)
        auth_name = auth_cursor.fetchall()

        for i in range(len(auth_name)):
            if (i % 1000 == 0):
                self.connection.commit()
#                 print "##############################################"
#                 print "layer 1 %.2f" % (100 * float(i) / len(auth_name)) + "%updated"
#                 print "##############################################"

            core_name = auth_name[i][0]
            core_field = auth_name[i][1]
            core_citation = int(auth_name[i][2])

            # print "UPDATING "+ core_field + ":" + core_name
            # intial score
            score = float(core_citation)
            # print "--intial score:%f" % score

            # search for layer 1
            co_cursor = self.connection.cursor()
            co_sql = '''SELECT id1,id2,publish_year,cnt FROM new_CoauthorFieldCntYear 
                          WHERE ((id1 = "%s" OR id2 = "%s") AND field = "%s");
                          ''' % (core_name, core_name, core_field)

            co_cursor.execute(co_sql)
            co_name = co_cursor.fetchall()

            expsum = 0.0
            countsum = 0.0
            # updating first layer
            for j in range(len(co_name)):
                layer_co_year = int(co_name[j][2])
                if (layer_co_year < self.start_year
                        or layer_co_year > self.end_year):
                    # print "skip for year"
                    continue

                if (co_name[j][0] == core_name):
                    layer_name = co_name[j][1]
                else:
                    layer_name = co_name[j][0]

                layer_co_cnt = int(co_name[j][3])
                # print "--%d papers with %s in %d" % (layer_co_cnt,layer_name,layer_co_year)

                layer_cursor = self.connection.cursor()

                layer_sql = """SELECT h_index,citation FROM new_AuthorFieldData
                              WHERE (author_id = "%s"AND field = "%s");""" % (
                    layer_name, core_field)
                layer_cursor.execute(layer_sql)
                temp = layer_cursor.fetchall()
                if (temp):
                    layer_count = float(temp[0][0])
                    layer_hindex = float(temp[0][1])
                else:
                    continue

                expsum += layer_co_cnt * e**(atan(layer_hindex))
                countsum += layer_co_cnt * layer_count * e**(
                    atan(layer_hindex))
            if (expsum != 0):
                score += countsum / expsum

            # outfile.write("%s %s %f\n" % (core_name, core_field, score))
            update_cursor = self.connection.cursor()
            update_sql = '''UPDATE new_AuthorFieldData
                            SET coauthor_factor_1 = %f
                            WHERE author_id = "%s" AND field = "%s";''' % (
                score, core_name, core_field)
            update_cursor.execute(update_sql)
            # print "--final score:%f" % score
        self.connection.commit()
Beispiel #35
0
	def update(self):
		global HERO_COUNT,L,R,GOLD_GAIN,GOLD_LOOSE,WIN,LOOSE,RESTART
		#enemydistance xy,walldistance xy,angle M[]6x1
		if self.side=="left":
			if 90>self.angle and self.angle>-90:
				found =False
				for i in range(len(hero.right_alives)):
					if hero.right_alives[i].alive:
						if degrees(atan(-((hero.right_alives[i].y)-(self.y+HERO_SIZE/2))/((hero.right_alives[i].x+HERO_SIZE)-(self.x+HERO_SIZE))))>=self.angle and self.angle>=degrees(atan(-((hero.right_alives[i].y+HERO_SIZE)-(self.y+HERO_SIZE/2))/((hero.right_alives[i].x+HERO_SIZE)-(self.x+HERO_SIZE)) )) and self.__distance(hero.right_alives[i])<=self.hook_range:
							self.layer1[0]=100
							hero.right_alives[i].layer1[1]=100
							found=True
							break
				if not found:
					self.layer1[0]=-100

			self.layer1[2:]=[self.x,left_side.size_x-self.x,self.y,HEIGHT-self.y,left_side.x+left_side.size_x-GOLD_AREA-self.x,self.angle,self.cooldown]
			if self.x+self.size_x>=left_side.x+SIZE_X-GOLD_AREA:
				if self.x==left_side.x+SIZE_X-self.size_x:
					self.score-=GOLD_LOOSE	
				else:
					self.score+=GOLD_GAIN
			else:
				self.score-=GOLD_LOOSE

		elif self.side=="right":	
			if not(90>self.angle and self.angle>-90):
				found =False
				for i in range(len(hero.left_alives)):
					if hero.left_alives[i].alive:
						if degrees(atan(-((self.y+HERO_SIZE/2)-(hero.left_alives[i].y+HERO_SIZE))/((self.x)-(hero.left_alives[i].x))))>=self.angle-180 and self.angle-180>=degrees(atan(-((self.y+HERO_SIZE/2)-(hero.left_alives[i].y))/((self.x)-(hero.left_alives[i].x)) )) and self.__distance(hero.left_alives[i])<=self.hook_range:
							self.layer1[0]=100
							hero.left_alives[i].layer1[1]=100
							found=True
							break
				if not found:
					self.layer1[0]=-100			
			self.layer1[2:]=[self.x-right_side.x,right_side.x+right_side.size_x-self.x,self.y,HEIGHT-self.y,right_side.x+GOLD_AREA-self.x,self.angle,self.cooldown]
			if self.x<=right_side.x+GOLD_AREA:
				if self.x == right_side.x:
					self.score-=GOLD_LOOSE
				else:
					self.score+=GOLD_GAIN
			else:
				self.score-=GOLD_LOOSE
		self.layer2=[100 if sum([self.weight1[i][j]*(self.layer1[j]+self.bias1[i]) for j in range(9)])>=5 else -100 for i in range(20)]
		self.layer3=[100 if sum([self.weight2[i][j]*(self.layer2[j]+self.bias2[i]) for j in range(20)])>=5 else -100 for i in range(10)]

		if self.status=="MOVING":
			if self.movement_vector[0] < 0:
				if self.side=="left":
					if self.x-left_side.x >= -self.movement_vector[0]:
						self.x+=self.movement_vector[0]
					else:
						self.x=left_side.x
				elif self.side=="right":
					if self.x-right_side.x >= -self.movement_vector[0]:
						self.x+=self.movement_vector[0]
					else:
						self.x=right_side.x
			elif self.movement_vector[0] > 0:
				if self.side=="left":
					if left_side.x+SIZE_X-HERO_SIZE-self.x >= self.movement_vector[0]:
						self.x+=self.movement_vector[0]
					else:
						self.x=left_side.x+SIZE_X-HERO_SIZE
				elif self.side=="right":
					if right_side.x+SIZE_X-HERO_SIZE-self.x >= self.movement_vector[0]:
						self.x+=self.movement_vector[0]
					else:
						self.x=right_side.x+SIZE_X-HERO_SIZE
			if self.movement_vector[1] < 0:
				if self.y >= -self.movement_vector[1]:
					self.y+=self.movement_vector[1]
				else:
					self.y=0
			elif self.movement_vector[1] > 0:
				if SIZE_Y-HERO_SIZE-self.y >= self.movement_vector[1]:
					self.y+=self.movement_vector[1]
				else:
					self.y=SIZE_Y-HERO_SIZE

		elif self.status=="HOOKING":

			self.hook_animation_time+=1
			
			if self.side=="left":
				for enemy in hero.right_heroes:
					if enemy.alive and enemy.x <= self.x+HERO_SIZE+self.hook_vector[0]*self.hook_animation_time+self.hook_size and enemy.x+HERO_SIZE >= self.x+HERO_SIZE+self.hook_vector[0]*self.hook_animation_time+self.hook_size and ((enemy.y <= self.y+HERO_SIZE/2-self.hook_size/2+self.hook_vector[1]*self.hook_animation_time and enemy.y+HERO_SIZE >= self.y+HERO_SIZE/2-self.hook_size/2+self.hook_vector[1]*self.hook_animation_time) or (enemy.y <= self.y+HERO_SIZE/2+self.hook_vector[1]*self.hook_animation_time and enemy.y+HERO_SIZE >= self.y+HERO_SIZE/2+self.hook_vector[1]*self.hook_animation_time)):
					   self.score+=20
					   enemy.score-=20
			
			elif self.side=="right":
				for enemy in hero.left_heroes:
					if enemy.alive and enemy.x <= self.x+self.hook_vector[0]*self.hook_animation_time-self.hook_size and enemy.x+HERO_SIZE >= self.x+self.hook_vector[0]*self.hook_animation_time-self.hook_size and ((enemy.y <= self.y+HERO_SIZE/2-self.hook_size/2+self.hook_vector[1]*self.hook_animation_time and enemy.y+HERO_SIZE >= self.y+HERO_SIZE/2-self.hook_size/2+self.hook_vector[1]*self.hook_animation_time) or (enemy.y <= self.y+HERO_SIZE/2+self.hook_size/2+self.hook_vector[1]*self.hook_animation_time and enemy.y+HERO_SIZE >= self.y+HERO_SIZE/2+self.hook_size/2+self.hook_vector[1]*self.hook_animation_time)):
					   self.score+=20
					   enemy.score-=20

			


			if self.hook_animation_time>=self.hook_duration:
				self.hook_animation_time=0
				self.status="IDLE"
		elif self.status=="IDLE":
			pass

		if self.score<=LOOSE:
			if self.side=="left":
				L+=1
			else:
				R+=1
			self.alive=False
			#self.new_desicion()
		if self.score>=WIN:
			RESTART=True
		if self.y < 0:
			self.y=0
		elif self.y>SIZE_Y-HERO_SIZE:
			self.y=SIZE_Y-HERO_SIZE	
		if self.player:
			self.score=LOOSE+GOLD_LOOSE*2
		if self.cooldown>0:
			self.cooldown-=0.1
#shoulder to wrist position
k=((l_sw[0,0])*(l_sw[0,0])+(l_sw[1,0])*(l_sw[1,0])+(l_sw[2,0])*(l_sw[2,0]))
mag=math.sqrt((l_sw[0,0])*(l_sw[0,0])+(l_sw[1,0])*(l_sw[1,0])+(l_sw[2,0])*(l_sw[2,0]))
u_norm=l_sw/mag
theta_41=math.acos(l_se**2+l_we**2-k)/(2*l_se*l_we)
theta_4=(pi-theta_41)
u_x=u_norm[0,0]
u_y=u_norm[1,0]
u_z=u_norm[2,0]
if theta_4_l<theta_4<theta_4_u:
    print('no solution')
else:
    skw=sp.Matrix([[0,-u_z,u_y],
                 [u_z,0,-u_x],
                 [-u_y,u_x,0]])
    theta_11=math.atan(w_y,w_x)
    alpha_1=math.asin((w_z-l_bs)/(l_sw))
    beta_2=math.acos((l_se**2+l_we**2 -l_we**2)/(2*l_se*l_we))
    theta_22=(pi/2)-alpha_1-beta_2
    R_01=sp.Matrix([[sp.cos(theta_11),0,-sp.sin(theta_11)],[sp.sin(theta_11),0,sp.cos(theta_11)],[0,-1,0]])
    R_12=sp.Matrix([[sp.cos(theta_22),0,sp.sin(theta_22)],[sp.sin(theta_22),0,-sp.cos(theta_22)],[0,1,0]])
    R_23=sp.Matrix([[1,0,0],[0,0,1],[0,-1,0]])
    R_03=R_01*R_02*R_23
    I=np.identity(3)
    skw2=sp.Matrix([[(u_z**2+u_y**2),(-u_x*u_y),(-u_x*u_z)],
                   [(-u_x*u_y),(u_x**2+u_z**2),(-u_z*u_y)],
                 [(-u_x*u_z),(-u_z*u_y),(u_y**2+u_x**2)]])
    X_S=skw*R_03
    Y_S=-(skw2)*R_03
    Z_S=(I+skw2)*R_03
import math
import time
import numpy as np
import GSASIIpath
GSASIIpath.SetVersionNumber("$Revision: 4028 $")
import GSASIIlattice as G2lat
import GSASIIpwd as G2pwd
import GSASIIspc as G2spc
import GSASIImath as G2mth
import scipy.optimize as so

# trig functions in degrees
sind = lambda x: math.sin(x * math.pi / 180.)
asind = lambda x: 180. * math.asin(x) / math.pi
tand = lambda x: math.tan(x * math.pi / 180.)
atand = lambda x: 180. * math.atan(x) / math.pi
atan2d = lambda y, x: 180. * math.atan2(y, x) / math.pi
cosd = lambda x: math.cos(x * math.pi / 180.)
acosd = lambda x: 180. * math.acos(x) / math.pi
rdsq2d = lambda x, p: round(1.0 / math.sqrt(x), p)
#numpy versions
npsind = lambda x: np.sin(x * np.pi / 180.)
npasind = lambda x: 180. * np.arcsin(x) / math.pi
npcosd = lambda x: np.cos(x * math.pi / 180.)
nptand = lambda x: np.tan(x * math.pi / 180.)
npatand = lambda x: 180. * np.arctan(x) / np.pi
npatan2d = lambda y, x: 180. * np.arctan2(y, x) / np.pi
rpd = np.pi / 180.


def scaleAbyV(A, V):
    def __init__(self,
                 amp=1.,
                 phib=25. * _degtorad,
                 p=1.,
                 phio=0.01,
                 m=4,
                 r1=1.,
                 rb=None,
                 cp=None,
                 sp=None,
                 ro=None,
                 vo=None):
        """
        NAME:

           __init__

        PURPOSE:

           initialize an cosmphi disk potential

        INPUT:

           amp= amplitude to be applied to the potential (default:
           1.), degenerate with phio below, but kept for overall
           consistency with potentials

           m= cos( m * (phi - phib) ), integer

           p= power-law index of the phi(R) = (R/Ro)^p part

           r1= (1.) normalization radius for the amplitude (can be Quantity); amp x phio is only the potential at (R,phi) = (r1,pib) when r1 > rb; otherwise more complicated

           rb= (None) if set, break radius for power-law: potential R^p at R > Rb, R^-p at R < Rb, potential and force continuous at Rb


           Either:
           
              a) phib= angle (in rad; default=25 degree; or can be Quantity)

                 phio= potential perturbation (in terms of phio/vo^2 if vo=1 at Ro=1; or can be Quantity with units of velocity-squared)
                 
              b) cp, sp= m * phio * cos(m * phib), m * phio * sin(m * phib); can be Quantity with units of velocity-squared)

        OUTPUT:

           (none)

        HISTORY:

           2011-10-27 - Started - Bovy (IAS)

           2017-09-16 - Added break radius rb - Bovy (UofT)

        """
        planarPotential.__init__(self, amp=amp, ro=ro, vo=vo)
        if _APY_LOADED and isinstance(phib, units.Quantity):
            phib = phib.to(units.rad).value
        if _APY_LOADED and isinstance(r1, units.Quantity):
            r1 = r1.to(units.kpc).value / self._ro
        if _APY_LOADED and isinstance(rb, units.Quantity):
            rb = rb.to(units.kpc).value / self._ro
        if _APY_LOADED and isinstance(phio, units.Quantity):
            phio = phio.to(units.km**2 / units.s**2).value / self._vo**2.
        if _APY_LOADED and isinstance(cp, units.Quantity):
            cp = cp.to(units.km**2 / units.s**2).value / self._vo**2.
        if _APY_LOADED and isinstance(sp, units.Quantity):
            sp = sp.to(units.km**2 / units.s**2).value / self._vo**2.
        # Back to old definition
        self._r1p = r1**p
        self._amp /= self._r1p
        self.hasC = False
        self._m = int(m)  # make sure this is an int
        if cp is None or sp is None:
            self._phib = phib
            self._mphio = phio * self._m
        else:
            self._mphio = math.sqrt(cp * cp + sp * sp)
            self._phib = math.atan(sp / cp) / self._m
            if m < 2. and cp < 0.:
                self._phib = math.pi + self._phib
        self._p = p
        if rb is None:
            self._rb = 0.
            self._rbp = 1.  # never used, but for p < 0 general expr fails
            self._rb2p = 1.
        else:
            self._rb = rb
            self._rbp = self._rb**self._p
            self._rb2p = self._rbp**2.
        self._mphib = self._m * self._phib
        self.hasC = True
        self.hasC_dxdv = True
Beispiel #39
0
 def restart(self, position, speed):
     self.position = position
     self.speed = speed
     self.direction = math.atan(speed[1] / speed[0])
Beispiel #40
0
    def _get_rupture_surface(self, mag, nodal_plane, hypocenter):
        """
        Create and return rupture surface object with given properties.

        :param mag:
            Magnitude value, used to calculate rupture dimensions,
            see :meth:`_get_rupture_dimensions`.
        :param nodal_plane:
            Instance of :class:`openquake.hazardlib.geo.nodalplane.NodalPlane`
            describing the rupture orientation.
        :param hypocenter:
            Point representing rupture's hypocenter.
        :returns:
            Instance of :class:`~openquake.hazardlib.geo.surface.planar.PlanarSurface`.
        """
        assert self.upper_seismogenic_depth <= hypocenter.depth \
            and self.lower_seismogenic_depth >= hypocenter.depth
        rdip = math.radians(nodal_plane.dip)

        # precalculated azimuth values for horizontal-only and vertical-only
        # moves from one point to another on the plane defined by strike
        # and dip:
        azimuth_right = nodal_plane.strike
        azimuth_down = (azimuth_right + 90) % 360
        azimuth_left = (azimuth_down + 90) % 360
        azimuth_up = (azimuth_left + 90) % 360

        rup_length, rup_width = self._get_rupture_dimensions(mag, nodal_plane)
        # calculate the height of the rupture being projected
        # on the vertical plane:
        rup_proj_height = rup_width * math.sin(rdip)
        # and it's width being projected on the horizontal one:
        rup_proj_width = rup_width * math.cos(rdip)

        # half height of the vertical component of rupture width
        # is the vertical distance between the rupture geometrical
        # center and it's upper and lower borders:
        hheight = rup_proj_height / 2.
        # calculate how much shallower the upper border of the rupture
        # is than the upper seismogenic depth:
        vshift = self.upper_seismogenic_depth - hypocenter.depth + hheight
        # if it is shallower (vshift > 0) than we need to move the rupture
        # by that value vertically.
        if vshift < 0:
            # the top edge is below upper seismogenic depth. now we need
            # to check that we do not cross the lower border.
            vshift = self.lower_seismogenic_depth - hypocenter.depth - hheight
            if vshift > 0:
                # the bottom edge of the rupture is above the lower sesmogenic
                # depth. that means that we don't need to move the rupture
                # as it fits inside seismogenic layer.
                vshift = 0
            # if vshift < 0 than we need to move the rupture up by that value.

        # now we need to find the position of rupture's geometrical center.
        # in any case the hypocenter point must lie on the surface, however
        # the rupture center might be off (below or above) along the dip.
        rupture_center = hypocenter
        if vshift != 0:
            # we need to move the rupture center to make the rupture fit
            # inside the seismogenic layer.
            hshift = abs(vshift / math.tan(rdip))
            rupture_center = rupture_center.point_at(
                horizontal_distance=hshift,
                vertical_increment=vshift,
                azimuth=(azimuth_up if vshift < 0 else azimuth_down))

        # from the rupture center we can now compute the coordinates of the
        # four coorners by moving along the diagonals of the plane. This seems
        # to be better then moving along the perimeter, because in this case
        # errors are accumulated that induce distorsions in the shape with
        # consequent raise of exceptions when creating PlanarSurface objects
        # theta is the angle between the diagonal of the surface projection
        # and the line passing through the rupture center and parallel to the
        # top and bottom edges. Theta is zero for vertical ruptures (because
        # rup_proj_width is zero)
        theta = math.degrees(
            math.atan((rup_proj_width / 2.) / (rup_length / 2.)))
        hor_dist = math.sqrt((rup_length / 2.)**2 + (rup_proj_width / 2.)**2)

        left_top = rupture_center.point_at(
            horizontal_distance=hor_dist,
            vertical_increment=-rup_proj_height / 2.,
            azimuth=(nodal_plane.strike + 180 + theta) % 360)
        right_top = rupture_center.point_at(
            horizontal_distance=hor_dist,
            vertical_increment=-rup_proj_height / 2.,
            azimuth=(nodal_plane.strike - theta) % 360)
        left_bottom = rupture_center.point_at(
            horizontal_distance=hor_dist,
            vertical_increment=rup_proj_height / 2.,
            azimuth=(nodal_plane.strike + 180 - theta) % 360)
        right_bottom = rupture_center.point_at(
            horizontal_distance=hor_dist,
            vertical_increment=rup_proj_height / 2.,
            azimuth=(nodal_plane.strike + theta) % 360)

        return PlanarSurface(self.rupture_mesh_spacing, nodal_plane.strike,
                             nodal_plane.dip, left_top, right_top,
                             right_bottom, left_bottom)
Beispiel #41
0
def dubins(alpha,beta,d,start_p):
    # find distance between start and end points
    #print "dubins d ",d," alpha ",alpha, " beta ", beta
    lengths = [-1.0,-1.0,-1.0,-1.0,-1.0,-1.0]
    t       = [-1.0,-1.0,-1.0,-1.0,-1.0,-1.0]
    p       = [-1.0,-1.0,-1.0,-1.0,-1.0,-1.0]
    q       = [-1.0,-1.0,-1.0,-1.0,-1.0,-1.0]
    sin_alpha = math.sin(alpha)
    cos_alpha = math.cos(alpha)
    sin_beta = math.sin(beta)
    cos_beta = math.cos(beta)
    cos_alphaminusbeta = math.cos(alpha - beta)
    

    # find length of curve 1: Left Straight Left                     [Lq(Sp(Lt(0,0,alpha))) = (d,0,beta)]
    tmp0 = d+sin_alpha-sin_beta;
    tmp2 = 2 + (d*d) - (2*cos_alphaminusbeta) + (2*d*(sin_alpha - sin_beta))
    if(tmp2 >= 0) and (tmp0 > 0):
        tmp1 = math.atan((cos_beta - cos_alpha)/tmp0)
        t[0]    = mod2pi(-alpha + tmp1)
        p[0]    = math.sqrt(tmp2)
        q[0]    = mod2pi(beta - tmp1)
        lengths[0] = t[0] + p[0] + q[0]
    #print "LSL ",lengths[0]
    #print "t = ",t[0]," p = ",p[0]," q = ",q[0]


    # find length of curve 2: Right Straight Right                    [Rq(Sp(Rt(0,0,alpha))) = (d,0,beta)]
    tmp0 = d - sin_alpha + sin_beta
    tmp2 = 2 + (d*d) - 2*cos_alphaminusbeta + (2*d*(sin_beta - sin_alpha))
    if(tmp2 >= 0 and tmp0 > 0):
        tmp1 = math.atan((cos_alpha - cos_beta)/tmp0)
        t[1]    = mod2pi(alpha - tmp1)
        p[1]    = math.sqrt(tmp2)
        q[1]    = mod2pi(-beta + tmp1)
        lengths[1] = t[1] + p[1] + q[1]
    #print "RSR ",lengths[1]
    #print "t = ",t[1]," p = ",p[1]," q = ",q[1]

    # find length of curve 3: Left Straight Right                     [Rq(Sp(Lt(0,0,alpha))) = (d,0,beta)]
    tmp1 = -2 + (d*d) + (2*cos_alphaminusbeta) + (2*d*(sin_alpha + sin_beta))
    if(tmp1 >= 0):
        p[2] = math.sqrt(tmp1)
        tmp2 = math.atan((-cos_alpha-cos_beta)/(d+sin_alpha+sin_beta)) - math.atan(-2.0/p[2])
        t[2] = mod2pi(-alpha + tmp2)
        q[2] = mod2pi( - mod2pi(beta) + tmp2)
        lengths[2] = t[2] + p[2] + q[2]
    #print "LSR ",lengths[2]
    #print "t = ",t[2]," p = ",p[2]," q = ",q[2]

    # find length of curve 4: Right Straight Left                      [Lq(Sp(Rt(0,0,alpha))) = (d,0,beta)]
    tmp1 = (d*d) - 2.0 + (2*cos_alphaminusbeta) - (2*d*(sin_alpha + sin_beta))
    if(tmp1 > 0):
        p[3] = math.sqrt(tmp1)
        tmp2 = math.atan((cos_alpha + cos_beta)/(d - sin_alpha - sin_beta)) - math.atan(2.0/p[3])
        t[3] = mod2pi(alpha - tmp2)
        q[3] = mod2pi(beta - tmp2)
        lengths[3] = t[3] + p[3] + q[3]
    #print "RSL ",lengths[3]
    #print "t = ",t[3]," p = ",p[3]," q = ",q[3]

    # find length of curve 5: Right Left Right                         [Rq(Lp(Rt(0,0,alpha))) = (d,0,beta)]
    tmp_rlr = (6.0 - d*d + 2.0*cos_alphaminusbeta + 2.0 * d * (sin_alpha - sin_beta))/8.0
    if(math.fabs(tmp_rlr) < 1):
        p[4] = math.acos(tmp_rlr)
        t[4] = mod2pi(alpha - math.atan2((cos_alpha - cos_beta),(d-sin_alpha + sin_beta)) + mod2pi(p[4]/2.0))
        q[4] = mod2pi(alpha - beta - t[4] + mod2pi(p[4]))
        lengths[4] = t[4] + p[4] + q[4]
    #print "RLR ",lengths[4]
    #print "t = ",t[4]," p = ",p[4]," q = ",q[4]
    
    # find length of curve 6: Left Right Left                          [Lq(Rp(Lt(0,0,alpha))) = (d,0,beta)]
    tmp_lrl = (6.0 - d*d + 2*cos_alphaminusbeta + 2*d*(-sin_alpha + sin_beta))/8.0
    if(math.fabs(tmp_lrl) < 1):
        p[5] = mod2pi(math.acos(tmp_lrl))
        t[5] = mod2pi(-alpha - math.atan2((cos_alpha - cos_beta),(d + sin_alpha - sin_beta)) + p[5]/2.0)
        q[5] = mod2pi(mod2pi(beta) - alpha - t[5] + mod2pi(p[5]))
        lengths[5] = t[5] + p[5] + q[5]
    #print "LRL ",lengths[5]
    #print "t = ",t[5]," p = ",p[5]," q = ",q[5]

    # find curve with minimum length
    i = 0
    for length in lengths:
        if(length >= 0): 
            min_length = length
            curve_number = i

    i = 0
    for length in lengths:
        if((length <= min_length) and (length >= 0)):
            min_length = length
            curve_number = i
        i=i+1                     
    
    if(isSafeDubins(curve_number,t[curve_number],p[curve_number],q[curve_number],start_p)):
        #print "Curve with min length is",curve_number
        return (curve_number,t[curve_number],p[curve_number],q[curve_number]) 
    else:
        return (-1,-1,-1,-1)
Beispiel #42
0
def main(thrust_lbf, innerRadius_in, fuel_mass_lb, dry_rocket_mass_lb):
    def cd_altitude_calc():

        slope_a = (224 - 293) / 11000  #kelvin decrease per meter

        if height < 11000:  #calculates the temperature at a given height
            altitude_temperature = mojave_temperature - (
                height * meters_to_feet * temp_slope)
            altitude_density = (1.225) * (altitude_temperature / 293)**(-(
                (9.8) / (slope_a * 287) + 1))
        else:  #above 11k meters the temperature is relatively constant
            altitude_temperature = mojave_temperature - (
                11000 * meters_to_feet * temp_slope)
            pressure_1 = (1.013e5) * (
                (altitude_temperature / 293)**(-9.8 / (slope_a * 287)))
            density_1 = (1.225) * (altitude_temperature / 293)**(-(
                (9.8) / (slope_a * 287) + 1))
            pressure_2 = (pressure_1) * real_e**(-9.8 * (height - 11000) /
                                                 (287 * 224))
            altitude_density = density_1 * (pressure_2 / pressure_1)

        altitude_mach = sqrt(
            gamma * gas_constant *
            altitude_temperature)  #mach from temperature, in m/s

        cd_v3_list = np.array([
            0.55432, 0.53437, 0.51071, 0.48687, 0.49139, 0.48243, 0.47812,
            0.47577, 0.46904, 0.49098, 0.51463, 0.68300, 0.67543, 0.62601,
            0.52901, 0.46041, 0.37132, 0.35000
        ])
        drag_v3_list = np.array([
            0, 8.77484, 33.31318, 72.91437, 127.70369, 197.82749, 283.87060,
            387.60258, 511.45387, 579.75506, 691.77405, 1084.06154, 1267.29417,
            1426.57258, 1969.45133, 2425.65958, 3757.03066
        ])
        drag_v4_list = np.array([
            0, 8.52192, 32.28034, 70.80437, 123.82969, 191.56966, 274.50500,
            374.45160, 493.56528, 671.10050, 833.52275, 1338.57703, 1416.65956,
            1556.88359, 2128.89588, 2777.19525, 3783.07444
        ])
        v_list = np.array([
            0, 33, 66, 99, 132, 165, 198, 231, 264, 280, 310, 345, 360, 400,
            500, 600, 800, 1200
        ])

        cd_list = []
        for x in range(0, len(v_list) - 1, 1):
            cd = (drag_v4_list[x]) / (0.5 * rho_0 * pi * 3.25**2 * 0.0254**2 *
                                      (v_list[x] + 0.001)**2)
            cd_list.append(cd)

        mach_list = v_list / solidworks_sos
        re_list = (v_list * rocket_length * rho_0) / solidworks_mu
        current_mach = velocity / altitude_mach  #mach at any given point, ranges from 0 - 2.3ish

        if current_mach < 0.3:  #defined as the mach at which the mach number plays more role than re
            altitude_mu = mu_0 * (altitude_temperature / t_0)**1.5 * (
                t_0 + s_0) / (altitude_temperature + s_0)
            current_re = velocity * altitude_density * rocket_length / altitude_mu
            for i in range(0, len(re_list), 1):
                if current_re >= re_list[i] and current_re <= re_list[i + 1]:
                    m = (cd_list[i + 1] - cd_list[i]) / (re_list[i + 1] -
                                                         re_list[i])
                    current_cd = (current_re - re_list[i]) * m + cd_list[i]
                    break
                else:
                    continue
        else:
            for i in range(0, len(mach_list), 1):
                if current_mach >= mach_list[i] and current_mach <= mach_list[
                        i + 1]:
                    m = (cd_list[i + 1] - cd_list[i]) / (mach_list[i + 1] -
                                                         mach_list[i])
                    current_cd = (current_mach - mach_list[i]) * m + cd_list[i]
                    break
                else:
                    continue

        return altitude_temperature, altitude_density, current_mach, current_cd

    def force_calc():

        force_gravity = ((gravitational_constant * (total_rocket_mass) *
                          (earth_mass)) / (mojave_radius + height)**2)
        force_drag = (0.5 * current_cd * altitude_density * velocity**2 *
                      rocket_area)

        return force_gravity, force_drag

    def append_lists():

        acceleration_list.append(acceleration)
        velocity_list.append(velocity)
        height_list.append(height)
        time_list.append(time)

        drag_coefficient_list.append(current_cd)
        current_mach_list.append(current_mach)
        force_gravity_list.append(force_gravity)
        force_drag_list.append(force_drag)
        density_list.append(altitude_density)
        temperature_list.append(altitude_temperature)

    def plot_plots():

        color_list = []

        for x in range(0, 6, 1):
            color = "%04x" % random.randint(0, 0xFFFF)
            color_2 = '#F' + color + 'F'
            color_list.append(color_2)

        ft_list = np.asarray(height_list) * meters_to_feet
        plt.subplot(3, 2, 1)
        plt.plot(time_list, ft_list, color_list[0])
        plt.ylabel('Height (ft)')
        plt.suptitle('Insert Rocket Name', fontsize=16)

        fts_list = np.asarray(velocity_list) * meters_to_feet
        plt.subplot(3, 2, 3)
        plt.plot(time_list, fts_list, color_list[1])
        plt.ylabel('Velocity (ft/s)')

        ftss_list = np.asarray(acceleration_list) * meters_to_feet
        plt.subplot(3, 2, 5)
        plt.plot(time_list, ftss_list, color_list[2])
        plt.ylabel('Acceleration (ft/s^2)')
        plt.xlabel('Time (s)')

        plt.subplot(3, 2, 2)
        plt.plot(current_mach_list, drag_coefficient_list, color_list[3])
        plt.ylabel('Drag Coefficient')
        plt.xlabel('Altitude Mach')

        g_lbf_list = np.asarray(force_gravity_list) / lbf_to_n
        plt.subplot(3, 2, 4)
        plt.plot(time_list, g_lbf_list, color_list[4])
        plt.ylabel('Force of Gravity (lbf)')
        plt.xlabel('Time (s)')

        d_lbf_list = np.asarray(force_drag_list) / lbf_to_n
        plt.subplot(3, 2, 6)
        plt.plot(time_list, d_lbf_list, color_list[5])
        plt.ylabel('Force of Drag (lbf)')
        plt.xlabel('Time (s)')

        plt.subplots_adjust(left=0.2, wspace=0.4, hspace=0.5, top=0.9)

        plt.show()

    """ Fundamental Constants """

    gravitational_constant = 6.67408e-11  #constant capital G
    boltzmann_constant = 1.38064852e-23  #in units of m^2 kg s^-2 K^-1
    gamma = 1.4
    gas_constant = 287.05  #J/(kg*K)
    solidworks_sos = 345.45  #calculated with values, m/s
    solidworks_mu = 1.8213e-5  #SolidWorks viscosity at 297K
    mu_0 = 1.716e-5  #kg/m-s, standard values`
    t_0 = 273.11  #K, used for altitude_viscosity calc
    s_0 = 110.56  #K, used for altitude_viscosity calc
    rho_0 = 1.1826  #kg/m^3, from SolidWorks
    meters_to_feet = 3.28084  #meter to feet conversion
    lbf_to_n = 4.4482216152605  #pound force to newton conversion
    lb_to_kg = 0.453592
    pa_to_psi = 0.000145038
    real_e = 2.71  #approximate value for e
    sealevel_pressure = 101325  #atmospheric pressure at sea level in Pascals
    earth_mass = 5.972e24  #kilograms
    temp_slope = 2 / 1000  #temperature decreases by 2 degrees for every increase in 1000ft altitude
    dt = 0.05  #increments of time value
    """ Mojave Desert Specific Values """

    mojave_radius = 6371.13738e3  #distance in meters from mojave latitude (35 degrees) to center of earth
    mojave_temperature = 23.8889 + 273.15  #degrees kelvin, approximate for May 2020
    mojave_pressure = 100846.66  #pressure in Pascals, converted from mmHg
    avg_airmass = 28.95 / 6.022e20  #average mass of a single air molecule in kg
    wind_speed = 15.  #wind speed in m/s
    rail_height = 60 / meters_to_feet  #rail height in meters
    """ Rocket Constants """
    #converts all inputs from imperial to metric
    thrust = thrust_lbf * lbf_to_n  #convets thrust to N for calculations
    fuel_mass = fuel_mass_lb * lb_to_kg
    dry_rocket_mass = dry_rocket_mass_lb * lb_to_kg

    burn_time = 9208 / (
        thrust_lbf)  #estimated total burn time of liquid fuel, in seconds
    total_rocket_mass = fuel_mass + dry_rocket_mass  #total mass, in kg
    mass_change = (fuel_mass /
                   burn_time) * dt  #assuming constant change of mass

    rocket_radius = (innerRadius_in / 12) * (1 / meters_to_feet
                                             )  #radius of the rocket, meters
    rocket_area = pi * (rocket_radius**2)  #area from radius
    rocket_length = 12.3 / meters_to_feet  #in meters
    rocket_roughness = 3e-6  #surface roughness of carbon fiber in meters
    """ Initialize Variables """

    time = 0.0  #sets all variables to zero for start of the flight
    height = 0.0
    velocity = 0.0

    height_track = 0.0
    velocity_track = 0.0
    mach_track = 0.0
    q_track = 0.0

    acceleration_list = []  #sets empty lists to be filled with data
    velocity_list = []
    height_list = []
    time_list = []

    drag_coefficient_list = []
    current_mach_list = []
    force_gravity_list = []
    force_drag_list = []
    density_list = []
    temperature_list = []

    while time <= burn_time:

        if height > rail_height:
            weather_adjust_factor = cos(atan(wind_speed / velocity))

        altitude_temperature, altitude_density, current_mach, current_cd = cd_altitude_calc(
        )  #finds density and drag coefficient at any given iteration
        force_gravity, force_drag = force_calc(
        )  #finds gravity and drag at any time

        if height <= rail_height:
            acceleration = (
                thrust - force_gravity -
                force_drag) / total_rocket_mass  #finds resultant acceleration
        else:
            acceleration = (
                weather_adjust_factor * thrust - force_gravity -
                force_drag) / total_rocket_mass  #finds resultant acceleration
            if thrust < (force_drag + force_gravity):
                force_drag = thrust - force_gravity
                acceleration = (
                    weather_adjust_factor * thrust - force_gravity - force_drag
                ) / total_rocket_mass  #finds resultant acceleration
                print("Uh oh. Rocket's going down")

        velocity += (acceleration * dt)  #increment velocity by small steps
        height += (velocity * dt)  #same process for height
        time += dt  #increase total time by dt
        total_rocket_mass -= mass_change  #at this time the rocket is losing fuel mass

        if velocity > velocity_track:  #keeps track of the greatest total speed
            altitude_mach = sqrt(gamma * gas_constant *
                                 altitude_temperature)  #mach from temperature
            velocity_track = velocity
            mach_track = velocity / altitude_mach

        q = velocity**2 * altitude_density * 0.5
        if q > q_track:
            q_track = q

        append_lists()  #keep track of all data
        print(altitude_temperature)

    while time > burn_time:

        weather_adjust_factor = cos(atan(wind_speed / velocity))

        altitude_temperature, altitude_density, current_mach, current_cd = cd_altitude_calc(
        )
        force_gravity, force_drag = force_calc()

        acceleration = (-force_gravity - force_drag) / total_rocket_mass
        velocity += (acceleration * dt)
        height += (velocity * dt)
        time += dt

        height_adjust = weather_adjust_factor * height

        if height > height_track:  #stops the simulation when rocket is at apogee
            height_track = height
        else:
            break

        append_lists()
        print(altitude_temperature)
        print(altitude_density, (avg_airmass * altitude_pressure) /
              (altitude_temperature * gas_constant))

    print('')
    print("Max velocity =", round(velocity_track * meters_to_feet, 3), "ft/s")
    print("Max mach =", round(mach_track, 3))
    print("Max dynamic pressure =", round(q_track * pa_to_psi, 3), "psi")
    print("Max drag force =", round(max(force_drag_list) / lbf_to_n, 3), "lbf")
    print("Max acceleration =",
          round(max(acceleration_list) * meters_to_feet, 3), "ft/s^2")
    print("Apogee =", round(height_track * meters_to_feet, 3), "ft")
    print('')
    plot_plots()
Beispiel #43
0
a, b, x = map(int, input().split())

half = a ** 2 * b / 2

if x <= half:
    #a ** 2 * a * np.tan(theta) / 2 = x
    theta = np.arctan(2 * x /a**2/a)
    print(np.rad2deg(theta))
else:

import math
a,b,x = map(int,input().split())
if x >= a*a*b/2:
  ans = math.degrees(math.atan(2*b/a-2*x/a**3))
else:
  ans = math.degrees(math.atan(a*b**2/(2*x)))
print(ans)
    def render_curved(self, font, word_text):
        """
        use curved baseline for rendering word
        """
        wl = len(word_text)
        isword = len(word_text.split()) == 1

        # do curved iff, the length of the word <= 10
        if not isword or wl > 10 or np.random.rand() > self.p_curved:
            return self.render_multiline(font, word_text)

        # create the surface:
        lspace = font.get_sized_height() + 1
        lbound = font.get_rect(word_text)
        fsize = (round(2.0 * lbound.width), round(3 * lspace))
        surf = pygame.Surface(fsize, pygame.locals.SRCALPHA, 32)

        # baseline state
        mid_idx = wl // 2
        BS = self.baselinestate.get_sample()
        curve = [BS['curve'](i - mid_idx) for i in range(wl)]
        curve[mid_idx] = -np.sum(curve) / (wl - 1)
        rots = [
            -int(
                math.degrees(
                    math.atan(BS['diff'](i - mid_idx) / (font.size / 2))))
            for i in range(wl)
        ]

        bbs = []
        # place middle char
        rect = font.get_rect(word_text[mid_idx])
        rect.centerx = surf.get_rect().centerx
        rect.centery = surf.get_rect().centery + rect.height
        rect.centery += curve[mid_idx]
        ch_bounds = font.render_to(surf,
                                   rect,
                                   word_text[mid_idx],
                                   rotation=rots[mid_idx])
        ch_bounds.x = rect.x + ch_bounds.x
        ch_bounds.y = rect.y - ch_bounds.y
        mid_ch_bb = np.array(ch_bounds)

        # render chars to the left and right:
        last_rect = rect
        ch_idx = []
        for i in range(wl):
            #skip the middle character
            if i == mid_idx:
                bbs.append(mid_ch_bb)
                ch_idx.append(i)
                continue

            if i < mid_idx:  #left-chars
                i = mid_idx - 1 - i
            elif i == mid_idx + 1:  #right-chars begin
                last_rect = rect

            ch_idx.append(i)
            ch = word_text[i]

            newrect = font.get_rect(ch)
            newrect.y = last_rect.y
            if i > mid_idx:
                newrect.topleft = (last_rect.topright[0] + 2,
                                   newrect.topleft[1])
            else:
                newrect.topright = (last_rect.topleft[0] - 2,
                                    newrect.topleft[1])
            newrect.centery = max(
                newrect.height,
                min(fsize[1] - newrect.height, newrect.centery + curve[i]))
            try:
                bbrect = font.render_to(surf, newrect, ch, rotation=rots[i])
            except ValueError:
                bbrect = font.render_to(surf, newrect, ch)
            bbrect.x = newrect.x + bbrect.x
            bbrect.y = newrect.y - bbrect.y
            bbs.append(np.array(bbrect))
            last_rect = newrect

        # correct the bounding-box order:
        bbs_sequence_order = [None for i in ch_idx]
        for idx, i in enumerate(ch_idx):
            bbs_sequence_order[i] = bbs[idx]
        bbs = bbs_sequence_order

        # get the union of characters for cropping:
        r0 = pygame.Rect(bbs[0])
        rect_union = r0.unionall(bbs)

        # crop the surface to fit the text:
        bbs = np.array(bbs)
        surf_arr, bbs = crop_safe(pygame.surfarray.pixels_alpha(surf),
                                  rect_union,
                                  bbs,
                                  pad=5)
        surf_arr = surf_arr.swapaxes(0, 1)
        return surf_arr, word_text, bbs
Beispiel #45
0
g = -9.81 #meters/s^2
dt = .001 #seconds
distance_uncertainty = .333333 #meters
goal_y_min = 3 #meters
goal_y_max = 3.5 #meters
goal_y_avg = .5*goal_y_min+.5*goal_y_max #meters

while(1):
	if cv.waitKey(1) & 0xFF == ord('q'):
		break

	goal_x = cv.getTrackbarPos("goal_x", 'params')/15 #meters
	
	#theta = cv.getTrackbarPos("theta", 'params') #degrees
	theta = math.degrees(math.atan(2*goal_y_avg/goal_x)) #degrees

	#v_0 =  cv.getTrackbarPos("v_0", 'params')/10.0 #meters/s
	v_0 = math.sqrt((2*-g*goal_x/math.sin(math.radians(2*theta)))) #meters/s
	
	print("goal distance:", goal_x, theta, v_0)

	time = []
	x_pos = []
	y_pos = []
	x_vel = []
	y_vel = []
	
	xvel = v_0*math.cos(math.radians(theta)) #meters/s
	xpos = 0 #meters
	yvel = v_0*math.sin(math.radians(theta)) #meters/s
Beispiel #46
0
    def PreProcess(self):
        # Smooth sensor data
        if len(self.times) < 2 or len(self.altitudes) < len(self.times):
            return
        self.altitudes = SmoothData(self.altitudes, GAUSSIAN_SMOOTH_SDEV)
        self.heartRates = SmoothData(self.heartRates, GAUSSIAN_SMOOTH_SDEV)
        self.distances = SmoothData(self.distances, GAUSSIAN_SMOOTH_SDEV)

        # Calculate speeds
        self.speeds = [0] * len(self.times)
        self.slopes = [0] * len(self.times)
        self.vDistances = [0] * len(self.times)
        lastTime = 0
        lastDistance = 0
        lastAltitude = self.altitudes[0]
        for i in range(len(self.times)):
            distance = self.distances[i]
            self.totalDistance += distance
            vDistance = self.altitudes[i] - lastAltitude
            self.speeds[i] = distance / (self.times[i] - lastTime)

            # Handle slope here

            # Ignore negligible values
            if distance <= 0.1:
                distance = 0
            if abs(vDistance) < 0.1:
                vDistance = 0

            # Don't allow a rise when there was no horizontal distance traveled
            if distance == 0:
                vDistance = 0
            elif abs(vDistance
                     ) > 0.5 * distance:  # Don't allow more then 50% grade
                vDistance = 0.5 * distance * vDistance / abs(vDistance)

            # Calculate the horizontal distance
            if distance == 0:
                hDistance = 0
            else:
                hDistance = math.sqrt(distance * distance -
                                      vDistance * vDistance)

            self.distances[i] = distance
            self.vDistances[i] = vDistance

            # Now calculate the slope
            if hDistance == 0:
                self.slopes[i] = 0  # To avoid divide by zerp
            else:
                slope = math.atan(vDistance / hDistance)
                self.slopes[i] = slope

            lastTime = self.times[i]
            lastDistance = self.distances[i]
            lastAltitude = self.altitudes[i]

        # Smooth the speeds
        self.speeds = SmoothData(self.speeds, GAUSSIAN_SMOOT_SECONDARY_DATA)
        # Smooth the slopes
        self.slopes = SmoothData(self.slopes, GAUSSIAN_SMOOT_SECONDARY_DATA)
Beispiel #47
0
     valf = 21.8 * mag.magb[i] / sqrt(swepam.dens[i])
 else:
     valf = 0.
 if (swepam.vel[i] > 0. and swepam.temp[i] > 0.):
     colage = (6.4e8 * swepam.dens[i]) / (swepam.vel[i] *
                                          (swepam.temp[i])**1.5)
 else:
     colage = 0.
 if (valf > 0.):  # and colage>0.):
     p = getperiod(iondata[0].time[i], iondata[0].timeframe)
     if (mag.phi[i] != 0. and mag.theta[i] != 0.
             and swepam.vel[i] > 0.):
         tmpmag = acos(cos(mag.phi[i]) * cos(mag.theta[i]))
     else:
         tmpmag = 0.
     tmpbetashift = atan(
         sqrt(swepam.vely[i]**2 + swepam.velz[i]**2) / swepam.velx[i])
     nrtmpvel = 0.
     tmpvel = 0.
     for ion2 in iondata:
         if (ion2.vel[i] > 0. and ion2.dens[i][0] > 0.):
             tmpvel += ion2.vel[i] * ion2.dens[i][0]
             nrtmpvel += ion2.dens[i][0]
     if nrtmpvel > 0.:
         tmpvel /= nrtmpvel
     if tmpbetashift != 0.:
         vd = getvd(swepam.vel[i], tmpvel, tmpmag + tmpbetashift,
                    polarity[p])
     else:
         vd = 0.
     #if (((polarity[p]==-1 and tmpmag>pi/2+4*pi/16) or (polarity[p]==1 and tmpmag<pi/2-4*pi/16)) and o7o6[i][1]>0. and tmpvel>swepam.vel[i]-4*valf and tmpvel<swepam.vel[i]+4*valf):
     #if (((polarity[p]==-1 and tmpmag>pi/2+4.*pi/16) or (polarity[p]==1 and tmpmag<pi/2-4.*pi/16)) and wp1[i][1]>0. and tmpvel>swepam.vel[i]-4*valf and tmpvel<swepam.vel[i]+4*valf and vd>0. and sigphiarr[i][1]<pi/180.*12. and sigthetaarr[i][1]<pi/180.*12. and tmpmag!=0.):
Beispiel #48
0
 def get_angle(self, radius):
     angle = atan(self.wheel_base / radius) * self.steer_ratio * 1.5
     return max(self.min_angle, min(self.max_angle, angle))
 def __flyTask(self, task):
     curTime = task.time + task.info['launchTime']
     t = min(curTime, task.info['timeOfImpact'])
     pos = task.info['trajectory'].getPos(t)
     task.info['toon'].setPos(pos)
     shadowPos = Point3(pos)
     if t >= task.info['timeEnterTowerXY'] and t <= task.info['timeExitTowerXY'] and pos[2] >= self.tower.getPos(render)[2] + TOWER_HEIGHT:
         shadowPos.setZ(self.tower.getPos(render)[2] + TOWER_HEIGHT + SHADOW_Z_OFFSET)
     else:
         shadowPos.setZ(SHADOW_Z_OFFSET)
     self.dropShadowDict[task.info['avId']].setPos(shadowPos)
     vel = task.info['trajectory'].getVel(t)
     run = math.sqrt(vel[0] * vel[0] + vel[1] * vel[1])
     rise = vel[2]
     theta = self.__toDegrees(math.atan(rise / run))
     task.info['toon'].setHpr(task.info['hRot'], -90 + theta, 0)
     if task.info['avId'] == self.localAvId:
         lookAt = self.tower.getPos(render)
         lookAt.setZ(lookAt.getZ() - TOWER_HEIGHT / 2.0)
         towerPos = Point3(self.towerPos)
         towerPos.setZ(TOWER_HEIGHT)
         ttVec = Vec3(pos - towerPos)
         toonTowerDist = ttVec.length()
         multiplier = 0.0
         if toonTowerDist < TOON_TOWER_THRESHOLD:
             up = Vec3(0.0, 0.0, 1.0)
             perp = up.cross(vel)
             perp.normalize()
             if ttVec.dot(perp) > 0.0:
                 perp = Vec3(-perp[0], -perp[1], -perp[2])
             a = 1.0 - toonTowerDist / TOON_TOWER_THRESHOLD
             a_2 = a * a
             multiplier = -2.0 * a_2 * a + 3 * a_2
             lookAt = lookAt + perp * (multiplier * MAX_LOOKAT_OFFSET)
         foo = Vec3(pos - lookAt)
         foo.normalize()
         task.info['maxCamPullback'] = max(task.info['maxCamPullback'], CAMERA_PULLBACK_MIN + multiplier * (CAMERA_PULLBACK_MAX - CAMERA_PULLBACK_MIN))
         foo = foo * task.info['maxCamPullback']
         camPos = pos + Point3(foo)
         camera.setPos(camPos)
         camera.lookAt(pos)
     if task.info['haveWhistled'] == 0:
         if -vel[2] > WHISTLE_SPEED:
             if t < task.info['timeOfImpact'] - 0.5:
                 task.info['haveWhistled'] = 1
                 base.playSfx(self.sndWhizz)
     if t == task.info['timeOfImpact']:
         if task.info['haveWhistled']:
             self.sndWhizz.stop()
         self.dropShadowDict[task.info['avId']].reparentTo(hidden)
         avatar = self.getAvatar(task.info['avId'])
         if task.info['hitWhat'] == self.HIT_WATER:
             avatar.loop('neutral')
             self.splash.setPos(task.info['toon'].getPos())
             self.splash.setScale(2)
             self.splash.play()
             base.playSfx(self.sndHitWater)
             task.info['toon'].setHpr(task.info['hRot'], 0, 0)
             self.__somebodyWon(task.info['avId'])
         elif task.info['hitWhat'] == self.HIT_TOWER:
             toon = task.info['toon']
             pos = toon.getPos()
             ttVec = Vec3(pos - self.towerPos)
             ttVec.setZ(0)
             ttVec.normalize()
             h = rad2Deg(math.asin(ttVec[0]))
             toon.setHpr(h, 94, 0)
             deltaZ = TOWER_HEIGHT - BUCKET_HEIGHT
             sf = min(max(pos[2] - BUCKET_HEIGHT, 0), deltaZ) / deltaZ
             hitPos = pos + Point3(ttVec * (0.75 * sf))
             toon.setPos(hitPos)
             hitPos.setZ(hitPos[2] - 1.0)
             s = Sequence(Wait(0.5), toon.posInterval(duration=LAND_TIME - 0.5, pos=hitPos, blendType='easeIn'))
             self.toonIntervalDict[task.info['avId']] = s
             s.start()
             avatar.iPos()
             avatar.pose('slip-forward', 25)
             base.playSfx(self.sndHitTower)
         elif task.info['hitWhat'] == self.HIT_GROUND:
             task.info['toon'].setP(render, -150.0)
             self.dustCloud.setPos(task.info['toon'], 0, 0, -2.5)
             self.dustCloud.setScale(0.35)
             self.dustCloud.play()
             base.playSfx(self.sndHitGround)
             avatar.setPlayRate(2.0, 'run')
             avatar.loop('run')
         return Task.done
     return Task.cont
    def derivatives(self, t0, y0):
        self.n=len(self.world)

        yp=Vector(len(y0)) 
        vect_acc=Vector2(0,0)

        for i in range(self.n):

            print(i)
            corpsi=self.world._bodies[i]
            
            yp[self.dim*i]= y0[(self.n + i)*self.dim]
            yp[self.dim*i+1]= y0[(self.n + i)*self.dim+1]
            pos_i=Vector2(y0[self.dim*i],y0[self.dim*i+1])

            
        
            for j in range(i):
                
    
                vect_diff=pos_i - Vector2(y0[self.dim*j],y0[self.dim*j+1])
                d=vect_diff.norm()
                    
                corpsj=self.world._bodies[j]
                
                
                rij=(self.world._bodies[j].position-self.world._bodies[i].position)
                uij=Vector.norm(rij)*50
                
                
                ri=corpsi.draw_radius
                rj=corpsj.draw_radius
                
                R=ri+rj
                
    
                print(uij<R)
                print(uij)
                if uij<R:
                        
                    eij=rij/uij
                    nij=Rotation(pi/2,eij) #calcul 
                    
                    mi=corpsi.mass
                    mj=corpsj.mass
                    
                    c11=(mi-mj)/(mi+mj)
                    c12=(2*mj/(mi+mj))
                    c21=(mj-mi)/(mi+mj)
                    c22=(2*mi)/(mi+mj)
                    
                    
             
                    vi=Vector2(y0[(self.n + i)*self.dim],y0[(self.n + i)*self.dim+1])
                    
                    vj=Vector2(y0[(self.n + j)*self.dim],y0[(self.n + j)*self.dim+1])

                    thetai=acos(dot(vi,nij)/Vector.norm(vi)) #angles de collision
                    thetaj=acos(dot(vj,nij)/Vector.norm(vj))
                    
                    
                    
                    thetapi=atan(c11*tan(thetai)+c12*Vector.norm(vj)*sin(thetaj)/(cos(thetai)*Vector.norm(vi))) #angles de rebond
                    thetapj=atan(c21*tan(thetaj)+c22*Vector.norm(vi)*sin(thetai)/(cos(thetaj)*Vector.norm(vj)))
                    
                    
                    
                    vpi=sqrt((Vector.norm(vj)*c12*sin(thetaj)+c11*Vector.norm(vi)*sin(thetai))**2+Vector.norm(vi)*Vector.norm(vi)*cos(thetai)*cos(thetai)) #vitesse de rebond
                    vpj=sqrt((Vector.norm(vi)*c22*sin(thetai)+c21*Vector.norm(vj)*sin(thetaj))**2+Vector.norm(vj)*Vector.norm(vj)*cos(thetaj)*cos(thetaj))
                   
                    
                    
                    print(vpi)
                    print(vpj)
                    
                    y0[(self.n + i-1)*self.dim] = -vpi
                    y0[(self.n + i)*self.dim-1] = vpi
                    y0[self.dim*self.n + self.dim*(j+1) ] = vpj
                    y0[self.dim*self.n + self.dim*(j+1)+1 ] = -vpj
                    
                    
                    
                    
                    

    

                else:
                            vect_acc=(-G/(d*d*d))*vect_diff
                            yp[self.dim*self.n + self.dim*i ] += self.world._bodies[j].mass*vect_acc.get_x()
                            yp[self.dim*self.n + self.dim*i+1]+= self.world._bodies[j].mass*vect_acc.get_y()
                            yp[self.dim*self.n + self.dim*j ] += -self.world._bodies[i].mass*vect_acc.get_x()
                            yp[self.dim*self.n + self.dim*j+1]+= -self.world._bodies[i].mass*vect_acc.get_y()
                            print(yp)

        return yp
                # Flow vector
                vis = frame.copy()
                flowVectorLength = []
                flowVectorLength_x = []
                flowVectorLength_y = []
                flowAngle = []
                i = 0
                for (x0, y0), (x1, y1), good in zip(all_pixels[:, 0], p1[:, 0], st[:, 0]):
                    if i % 30 is 0:
                        if good:
                            cv2.line(vis, (x0, y0), (x1, y1), (0, 128, 0))
                        flowVectorLength.append(math.sqrt((x1 - x0) ** 2 + (y1 - y0) ** 2))
                        flowVectorLength_x.append(x1 - x0)
                        flowVectorLength_y.append(y1 - y0)
                        flowAngle.append(math.atan((y1 - y0) / (x1 - x0)))
                        vis = cv2.circle(vis, (x1, y1), 2, (red, green)[good], -1)
                    i = i + 1
                cv2.imshow('Dense LK', vis)

        # experirement using a feature based dectection
        elif method is "feature":
            # detect key feature points
            featureDetectorType = "ORB"
            if featureDetectorType is "SIFT":
                detector = cv2.xfeatures2d.SIFT_create()
                kp1 = detector.detect(im1)
                kp2 = detector.detect(im2)
            elif featureDetectorType is "SURF":
                detector = cv2.xfeatures2d.SURF_create()
                kp1 = detector.detect(im1)
Beispiel #52
0
import svgwrite
from astropy import units as u
from astropy.io import fits
from astropy.wcs import WCS
from astropy.coordinates import SkyCoord

hdu = fits.open(wcs_fits)[0]
w = WCS(hdu.header, fix=False)
image_w = hdu.header['IMAGEW']
image_h = hdu.header['IMAGEH']

sky_left = w.pixel_to_world(0, 0)
sky_right = w.pixel_to_world(image_w, 0)
sky_right2 = SkyCoord(ra=sky_right.ra, dec=sky_left.dec)
x2, y2 = w.world_to_pixel(sky_right2)
image_tilt = math.degrees(math.atan(y2 / x2))
print('tilt=', image_tilt)
scales = w.proj_plane_pixel_scales()
px_scale = (scales[0].to_value(unit=u.deg) +
            scales[1].to_value(unit=u.deg)) / 2
print('scale=', px_scale)

drw = svgwrite.Drawing(out_file, size=(image_w, image_h))
drw.add(drw.style(style_sheet))

#TBD: select embed or link by option.
embed_image = True
if embed_image:
    with open(image_file, 'rb') as f:
        mime = ''
        if image_file.upper().endswith('.JPG'):
Beispiel #53
0
#     a = math.atan(z[i]/R[i])
#     angle.append(math.degrees(a))


def rmax():
    thick = 2.
    r_diff_rad = math.sqrt(
        (sm_dia / 2)**2 + (big_dia / 2)**2 - 0.5 * sm_dia * big_dia *
        math.cos(math.radians(angle_circle_step / 2))) / 2 - 2 * thick - 1
    r_same_rad = sm_dia / 2 * math.tan(math.radians(
        angle_circle_step / 2)) - thick - 0.5
    return min(r_diff_rad, r_same_rad)


print(rmax())
a0 = math.atan((get_optimized_rad() - cree_rad - R[1]) / (Obj_dist - z[1]))
# refl_angle.append(math.degrees(a0))
# Rmax = R[1] + (zmax - z[1]) * math.tan(a0)
Rmax = rmax()
zmax = (rmax() - R[1]) / math.tan(a0) + z[1]
print('Максимальный радиус в верхней точке отражателя: ' +
      str(round(Rmax, 2)) + 'мм.')
a_max = math.atan(zmax / Rmax)
KPD = 100 * (get_optimized_rad() - cree_rad) / (Obj_dist / math.tan(a_max))
print('КПД отражателя: ' + str(round(KPD, 2)) + '%')
# da = (a_max - a)/(N-1)
b = math.pi / 2. - a
f = (b + a0) / 2.
e = b - f

Beispiel #54
0
 def latitude(y):
     lat_rad = math.atan(math.sinh(math.pi - 2 * math.pi * y / factor))
     return math.degrees(lat_rad)
Beispiel #55
0
def get_yaw_from_quarternion(q):
	siny_cosp = 2*(q.w*q.z + q.x*q.y)
	cosy_cosp=1-2*(q.y*q.y+q.z*q.z)
	yaw=math.atan(siny_cosp/cosy_cosp)
	return yaw
Beispiel #56
0
#1.fix x and fix spin in y z
#weihuajing @NanJing University

from yade import qt, pack, export
import math

#setting frict materials -----
fyoung = 8e9
fpoisson = 0.25
frictAng = 0
fden = 2500

#setting rock materials -----
ryoung = 2e7
rpoisson = 0.25
rfrictAng = math.atan(0.6)
reps = 0.06
rden = 2500

frict = O.materials.append(
    FrictMat(young=fyoung,
             poisson=fpoisson,
             frictionAngle=frictAng,
             density=fden))

temp_con = O.materials.append(
    CpmMat(young=ryoung,
           poisson=rpoisson,
           frictionAngle=rfrictAng,
           epsCrackOnset=1e-13,
           density=rden,
def annular(dataSet, radius, thx, save='0', describer=None, nbins=100, loc='py_annular_exp/'):

    radius = radius
    thx = thx

    mag = dataSet.q_data

    # Draw a set of x,y points for the circles chosen
    theta = np.linspace(0, 2*np.pi, 314)
    cx = radius*np.cos(theta)
    cy = radius*np.sin(theta)
    cxouter = (radius + thx)*np.cos(theta)
    cyouter = (radius + thx)*np.sin(theta)

    # Capture points that fall within the annular rings based on their magnitude

    I_ann = np.logical_and(radius < mag, mag < (radius+thx))
    annul_x = dataSet.qx_data[I_ann]
    annul_y = dataSet.qy_data[I_ann]
    annul_I = dataSet.data[I_ann]
    annul_err = dataSet.err_data[I_ann]
    annul_mag = dataSet.q_data[I_ann]

    # Calculate the angles for the obtained points. Zero is twleve o clock (vertically up on y-axis)

    annul_ang = []

    for i in range(len(annul_mag)):
        if annul_y[i] > 0:
            annul_ang.append(math.atan(annul_x[i]/annul_y[i]))
        elif annul_y[i] < 0:
            annul_ang.append(math.atan(annul_x[i]/annul_y[i]) + np.pi)

    annul_ang = np.array(annul_ang)

    # Sorts data to give as a function of increasing angle
    sortI = np.argsort(annul_ang)
    annul_ang = annul_ang[sortI]
    annul_mag = annul_mag[sortI]
    annul_x = annul_x[sortI]
    annul_y = annul_y[sortI]
    annul_I = annul_I[sortI]
    annul_err = annul_err[sortI]

    # Data binning
    nbsa = nbins
    # nbsa = 100
    deltheta = 2*np.pi/nbsa
    binsa = np.linspace(-np.pi/2, 3*np.pi/2, nbsa)

    binindexa = np.zeros([nbsa])  # number points summed per bin
    bintotala = np.zeros([nbsa])  # summed intensity
    errtotala = np.zeros([nbsa])  # summed error

    for i in range(nbsa - 1):
        for ii in range(len(annul_mag)):
            if annul_ang[ii] >= binsa[i]:
                if annul_ang[ii] <= binsa[i + 1]:
                    binindexa[i] = binindexa[i] + 1
                    bintotala[i] = bintotala[i] + annul_I[ii]
                    errtotala[i] = errtotala[i] + annul_err[ii]
#                print(errtotal[i])

    binZeros = binindexa != 0

    binsa = binsa[binZeros]
    binindexa = binindexa[binZeros]
    bintotala = bintotala[binZeros]
    errtotala = errtotala[binZeros]
#    print(errtotal)

    binavea = bintotala/binindexa
    erravea = errtotala/binindexa
#    print(errave)

    if save == '1':
        fileType = '.dat'
        # fileName = describer + '_' + \
        #     str(dataSet.sample[0]) + '_' + str(dataSet.shear[0][0:-14]) + 'ps'
        fileName = describer + '_' + \
            str(dataSet.sample[0]) + 'wt' + '_' + str(dataSet.shear) + 'ps'
        location = '../2D_annular_sector_extraction/' + loc
        fullName = location + fileName + fileType
        with open(fullName, 'wt') as fh:
            fh.write("q  I(q)  err_I\n")
            for x, y, z in zip(binsa, binavea, binavea):
                fh.write("%g  %g  %g\n" % (x, y, z))

    annul_data = []
    annul_data.append(annul_x)
    annul_data.append(annul_y)
    annul_data.append(annul_I)
    annul_data.append(I_ann)

    return binsa, binavea, erravea, annul_data
import math

tk=Tk()
canvas=Canvas(width=880,height=500,bg='black')
canvas.grid()
BGPic=PhotoImage(file='Background2.png')
MonkeyPic=PhotoImage(file='Monkey.png')
DartPic=PhotoImage(file='dart.png')
canvas.create_image(0,0,image=BGPic,anchor=NW)
monkey=canvas.create_image(810,147, image=MonkeyPic)
dart=canvas.create_image(180,300, image=DartPic)


canvas.pack()

Theta=math.atan((320-147)/(810-180))
V0=15
Vx=V0*math.cos(Theta)
Vy=-V0*math.sin(Theta)
Vym=0
g=.2
while True:
    canvas.move(monkey,0,Vym)
    canvas.move(dart,Vx,Vy)
    posM = canvas.coords(monkey)
    posD = canvas.coords(dart)
    Vym=Vym+g
    Vy=Vy+g
    if posM[1]>=400 :
        Vym=0
    if posD[0]>=posM[0]-55:
Beispiel #59
0
def CornerEstimationWithoutOffsets(packet):
    ''' Corner estimation without Offsets '''
    global defaultTargetWidth

    try:
        sensorLatitude = packet.GetSensorLatitude()
        sensorLongitude = packet.GetSensorLongitude()
        sensorTrueAltitude = packet.GetSensorTrueAltitude()
        frameCenterLat = packet.GetFrameCenterLatitude()
        frameCenterLon = packet.GetFrameCenterLongitude()
        frameCenterElevation = packet.GetFrameCenterElevation()
        sensorVerticalFOV = packet.GetSensorVerticalFieldOfView()
        sensorHorizontalFOV = packet.GetSensorHorizontalFieldOfView()
        headingAngle = packet.GetPlatformHeadingAngle()
        sensorRelativeAzimut = packet.GetSensorRelativeAzimuthAngle()
        targetWidth = packet.GettargetWidth()
        slantRange = packet.GetSlantRange()

        # If target width = 0 (occurs on some platforms), compute it with the slate range.
        # Otherwise it leaves the footprint as a point.
        if targetWidth == 0 and slantRange != 0:
            targetWidth = 2.0 * slantRange * \
                tan(radians(sensorHorizontalFOV / 2.0))
        elif targetWidth == 0 and slantRange == 0:
            # default target width to not leave footprint as a point.
            targetWidth = defaultTargetWidth
            qgsu.showUserAndLogMessage(QCoreApplication.translate(
                "QgsFmvUtils", "Target width unknown, defaults to: " +
                str(targetWidth) + "m."),
                                       level=QGis.Info)

        # compute distance to ground
        if frameCenterElevation != 0:
            sensorGroundAltitude = sensorTrueAltitude - frameCenterElevation
        else:
            qgsu.showUserAndLogMessage(QCoreApplication.translate(
                "QgsFmvUtils",
                "Sensor ground elevation narrowed to true altitude: " +
                str(sensorTrueAltitude) + "m."),
                                       level=QGis.Info)
            sensorGroundAltitude = sensorTrueAltitude

        if sensorLatitude == 0:
            return False

        initialPoint = (sensorLongitude, sensorLatitude)
        destPoint = (frameCenterLon, frameCenterLat)

        distance = sphere.distance(initialPoint, destPoint)
        if distance == 0:
            return False

        if sensorVerticalFOV > 0 and sensorHorizontalFOV > sensorVerticalFOV:
            aspectRatio = sensorVerticalFOV / sensorHorizontalFOV

        else:
            aspectRatio = 0.75

        value2 = (headingAngle + sensorRelativeAzimut) % 360.0  # Heading
        value3 = targetWidth / 2.0

        value5 = sqrt(pow(distance, 2.0) + pow(sensorGroundAltitude, 2.0))
        value6 = targetWidth * aspectRatio / 2.0

        degrees = rad2deg(atan(value3 / distance))

        value8 = rad2deg(atan(distance / sensorGroundAltitude))
        value9 = rad2deg(atan(value6 / value5))
        value10 = value8 + value9
        value11 = sensorGroundAltitude * tan(radians(value10))
        value12 = value8 - value9
        value13 = sensorGroundAltitude * tan(radians(value12))
        value14 = distance - value13
        value15 = value11 - distance
        value16 = value3 - value14 * tan(radians(degrees))
        value17 = value3 + value15 * tan(radians(degrees))
        distance2 = sqrt(pow(value14, 2.0) + pow(value16, 2.0))
        value19 = sqrt(pow(value15, 2.0) + pow(value17, 2.0))
        value20 = rad2deg(atan(value16 / value14))
        value21 = rad2deg(atan(value17 / value15))

        # CP Up Left
        bearing = (value2 + 360.0 - value21) % 360.0
        cornerPointUL = list(
            reversed(sphere.destination(destPoint, value19, bearing)))

        # CP Up Right
        bearing = (value2 + value21) % 360.0
        cornerPointUR = list(
            reversed(sphere.destination(destPoint, value19, bearing)))

        # CP Low Right
        bearing = (value2 + 180.0 - value20) % 360.0
        cornerPointLR = list(
            reversed(sphere.destination(destPoint, distance2, bearing)))

        # CP Low Left
        bearing = (value2 + 180.0 + value20) % 360.0
        cornerPointLL = list(
            reversed(sphere.destination(destPoint, distance2, bearing)))

        UpdateFootPrintData(cornerPointUL, cornerPointUR, cornerPointLR,
                            cornerPointLL)

        UpdateBeamsData(packet, cornerPointUL, cornerPointUR, cornerPointLR,
                        cornerPointLL)

        SetGCPsToGeoTransform(cornerPointUL, cornerPointUR, cornerPointLR,
                              cornerPointLL, frameCenterLon, frameCenterLat)
    except:
        return False

    return True
def sector(dataSet, centre, width, save='0', describer=None, nbins=100, loc='py_sect_radAve/'):

    xcentre = 0
    ycentre = 0

    sectcent = centre  # In radians
    sectwid = width  # In radians

    # dataSet should be a sasView 2D data object
    # data_sqrd = dataSet**2
    mag = dataSet.q_data  # q values
    sectang = []

    for i in range(len(mag)):
        if dataSet.qy_data[i] > 0:
            sectang.append(math.atan(dataSet.qx_data[i]/dataSet.qy_data[i]))
        elif dataSet.qy_data[i] < 0:
            sectang.append(math.atan(dataSet.qx_data[i]/dataSet.qy_data[i]) + np.pi)

    sectang = np.array(sectang)

    cwmax = sectcent+(0.5*sectwid)  # Max bound for top sector
    cwmin = sectcent-(0.5*sectwid)  # Min bound for top sector
    cwmax_ref = sectcent+(0.5*sectwid)+math.pi  # Max bound for bottom sector
    cwmin_ref = sectcent-(0.5*sectwid)+math.pi  # Min bound for bottom sector

    # Sorting according to angle
    sortI = np.argsort(sectang)
    sectang = sectang[sortI]
    mag = mag[sortI]
    err = dataSet.err_data[sortI]
    data = dataSet.data[sortI]

    seccrop_data = np.zeros_like(data)
    seccrop_err = np.zeros_like(err)
    seccrop_mag = np.zeros_like(mag)
    seccrop_ang = np.zeros_like(sectang)

    # Find logic gates
    posLog = np.logical_and(cwmin < sectang, sectang < cwmax)
    negLog = np.logical_and(cwmin_ref < sectang, sectang < cwmax_ref)

    # Find values according to logic gates
    seccrop_data[posLog] = data[posLog]
    seccrop_err[posLog] = err[posLog]
    seccrop_mag[posLog] = mag[posLog]
    seccrop_ang[posLog] = sectang[posLog]

    seccrop_data[negLog] = data[negLog]
    seccrop_err[negLog] = err[negLog]
    seccrop_mag[negLog] = mag[negLog]
    seccrop_ang[negLog] = sectang[negLog]

    zeros = seccrop_mag != 0  # Find zeros

    # remove zeros
    seccrop_data = seccrop_data[zeros]
    seccrop_err = seccrop_err[zeros]
    seccrop_mag = seccrop_mag[zeros]
    seccrop_ang = seccrop_ang[zeros]

    # Sort by ascending q
    sortq = np.argsort(seccrop_mag)

    seccrop_data = seccrop_data[sortq]
    seccrop_err = seccrop_err[sortq]
    seccrop_mag = seccrop_mag[sortq]
    seccrop_ang = seccrop_ang[sortq]

    # Make 100 bins spaced log linearly between min and max q
    nbs = nbins
    minMag = np.min(seccrop_mag)
    maxMag = np.max(seccrop_mag)

    logMinMag = np.log10(minMag)
    logMaxMag = np.log10(maxMag)

    logLinear = np.linspace(logMinMag, logMaxMag, nbs)
    bins = 10**logLinear

    binindex = np.zeros([nbs])  # number points summed per bin
    bintotal = np.zeros([nbs])  # summed intensity
    errtotal = np.zeros([nbs])  # summed error

    for i in range(nbs - 1):
        for ii in range(len(seccrop_data)):
            if seccrop_mag[ii] >= bins[i]:
                if seccrop_mag[ii] <= bins[i + 1]:
                    binindex[i] = binindex[i] + 1
                    bintotal[i] = bintotal[i] + seccrop_data[ii]
                    errtotal[i] = errtotal[i] + seccrop_err[ii]
#                print(errtotal[i])

    binZeros = binindex != 0

    bins = bins[binZeros]
    binindex = binindex[binZeros]
    bintotal = bintotal[binZeros]
    errtotal = errtotal[binZeros]
#    print(errtotal)

    binave = bintotal/binindex
    errave = errtotal/binindex

#    allerror = [err, seccrop_err, errtotal, errave]

    if save == '1':
        fileType = '.dat'
        fileName = describer + '_' + \
            str(dataSet.sample[0]) + 'wt' + '_' + str(dataSet.shear) + 'ps'
        location = '../2D_annular_sector_extraction/' + loc
        fullName = location + fileName + fileType
        with open(fullName, 'wt') as fh:
            fh.write("q  I(q)  err_I\n")
            for x, y, z in zip(bins, binave, errave):
                fh.write("%g  %g  %g\n" % (x, y, z))

    return bins, binave, errave