def shoot2(self, x, y, datum_point_x=7, datum_point_y=7, debug=False): # calculate the rotate angles quadrant = getQuadrant(x, y, datum_point_x, datum_point_y) print 'quadrant : %d' % quadrant xcoef = 1 if quadrant == 3 or quadrant == 4 else -1 ycoef = 1 if quadrant == 2 or quadrant == 4 else -1 base = abs(abs(x-datum_point_x) * self.gridLength - (xcoef * (self.gridLength / 2))) height = abs(abs(y-datum_point_y) * self.gridLength - (ycoef * (self.gridLength / 2))) laser2target = math.sqrt(pylab.square(base) + pylab.square(height) + pylab.square(self.laser2wall)) print "base : %f \t height : %f" % (base, height) print laser2target yaw = math.asin(base / laser2target) pitch = math.asin(height / laser2target) print "yaw : %f \t pitch : %f" % (yaw, pitch) units2yaw = yaw / anglePerStep units2pitch = pitch / anglePerStep if quadrant == 1 or quadrant == 3: units2yaw = -units2yaw if quadrant == 3 or quadrant == 4: units2pitch = -units2pitch print 'steps to yaw %f \t steps to pitch %f' % (units2yaw, units2pitch) self.move(units2yaw, units2pitch, 1, 3000) time.sleep(5) # return to the datum point self.move(-units2yaw, -units2pitch, 1, 0)
def rotate(sz,p,q,r): # determines current orientation based on gravity data # initial position vector v = np.array([0,0,r]) # Euler angles in degrees from the sensor # CCW +ve, CW -ve #need to check how things fall here '''a = (q) * pi/180 #-1.875 b = (p) * pi/180 #+.5 # Rotation matrix Ra = np.array([[1, 0 , 0 ],\ [0, m.cos(a),-m.sin(a)],\ [0, m.sin(a), m.cos(a)]]) Rb = np.array([[ m.cos(b), 0 , m.sin(b)],\ [ 0 , 1 , 0 ],\ [ -m.sin(b), 0 , m.cos(b)]]) R = np.dot(Ra,Rb)''' a = m.asin((q )/9.8)# + .0875#gets angle and accounts for bias in IMU reading b = m.asin((p )/9.8)# + .01438 R = np.array([[ (m.cos(b)) , 0, m.sin(b) ],\ [(-m.sin(a))*(m.sin(b)), m.cos(a), (m.sin(a))*(m.cos(b))],\ [(-m.sin(b))*(m.cos(a)), -m.sin(a), (m.cos(a))*(m.cos(b))]]) new_v = np.dot(R,v) return new_v
def monitorArms(self, task): anglesDict = {} for arm in self.arms: direction = self.ralph.get_pos() - arm.get_pos() direction.normalize() #print(direction) # camera starts facing along x dec = math.asin(direction.x) cosdec = math.cos(dec) if cosdec > 1e-05: ra = math.asin(clamp1(direction.z / cosdec)) ra2 = math.acos(clamp1(direction.y / cosdec)) else: ra = ra2 = math.pi/2 #print(cosdec, direction) #print 'arm ' + arm.get_name() + ' ' + str((dec, ra, ra2, cosdec)) if direction.z > 0: if ra2 < math.pi/2: ra2 = 0 else: ra2 = math.pi arm.jointForearm.setH(-dec * 180/math.pi) arm.jointBase.setP(-ra2 * 180/math.pi) dec = -arm.jointForearm.getH() / 90.0 * 300 + 512 ra = -arm.jointBase.getP() / 90.0 * 300 + 212 #print -arm.jointBase.getP(), -arm.jointBase.getH() baseID = arm.baseID anglesDict[baseID] = int(round(ra)) anglesDict[baseID+1] = int(round(dec)) servos.setAngle(anglesDict) return task.again
def _gen_texture_coords(self, tex_coords=None, mapping_type=TextureMappingConstants.SPHERICAL): if len(tex_coords) == 0 : tex_coords = [] fast = False if mapping_type == TextureMappingConstants.SPHERICAL: if fast: for norm in self._normals: u = norm.x / 2 + 0.5 v = norm.z / 2 + 0.5 tex_coords.append([u,v]) else: for norm in self._normals: u = math.asin(norm.x)/math.pi + 0.5 v = math.asin(norm.z)/math.pi + 0.5 tex_coords.append([u,v]) else: # Expand the texture coordinates array to match the format of the transformed vertex array new_tex_coords = [] for vi in range(len(self._vert_index)): v_ind = self._vert_index[vi] new_tex_coords.append(tex_coords[v_ind]) tex_coords = new_tex_coords self._tex_coords = tex_coords
def day_length(doy, yr_days, latitude): """ Daylength in hours Eqns come from Leuning A4, A5 and A6, pg. 1196 Reference: ---------- Leuning et al (1995) Plant, Cell and Environment, 18, 1183-1200. Parameters: ----------- doy : int day of year, 1=jan 1 yr_days : int number of days in a year, 365 or 366 latitude : float latitude [degrees] Returns: -------- dayl : float daylength [hrs] """ deg2rad = pi / 180.0 latr = latitude * deg2rad sindec = -sin(23.5 * deg2rad) * cos(2.0 * pi * (doy + 10.0) / yr_days) a = sin(latr) * sindec b = cos(latr) * cos(asin(sindec)) dayl = 12.0 * (1.0 + (2.0 / pi) * asin(a / b)) return dayl
def heading(self): self.update() truncate = [0,0,0] for i in range(X, Z+1): truncate[i] = math.copysign(min(math.fabs(self._accel[i]), 1.0), self._accel[i]) try: pitch = math.asin(-1*truncate[X]) roll = math.asin(truncate[Y]/math.cos(pitch)) if abs(math.cos(pitch)) >= abs(truncate[Y]) else 0 # set roll to zero if pitch approaches -1 or 1 self._tiltcomp[X] = self._mag[X] * math.cos(pitch) + self._mag[Z] * math.sin(pitch) self._tiltcomp[Y] = self._mag[X] * math.sin(roll) * math.sin(pitch) + \ self._mag[Y] * math.cos(roll) - self._mag[Z] * math.sin(roll) * math.cos(pitch) self._tiltcomp[Z] = self._mag[X] * math.cos(roll) * math.sin(pitch) + \ self._mag[Y] * math.sin(roll) + \ self._mag[Z] * math.cos(roll) * math.cos(pitch) self._tilt_heading = math.atan2(self._tiltcomp[Y], self._tiltcomp[X]) if self._tilt_heading < 0: self._tilt_heading += 2*math.pi if self._tilt_heading > 2*math.pi: self._heading -= 2*math.pi self._tilt_heading_degrees = round(math.degrees(self._tilt_heading),2) return self._tilt_heading_degrees except Exception: return None
def get_pos_command(self): ts = ovr.getTrackingState(self.session, ovr.getTimeInSeconds(), True) if ts.StatusFlags & (ovr.Status_OrientationTracked | ovr.Status_PositionTracked): pose = ts.HeadPose # Get queternions q0 = pose.ThePose.Orientation.w; q1 = pose.ThePose.Orientation.x; q2 = pose.ThePose.Orientation.y; q3 = pose.ThePose.Orientation.z; # Calculate Euler angles x = int(1500 + 637*math.asin(2*(q0*q1 - q3*q2))) #pitch y = int(1450 - 637*math.atan2(2*(q0*q2 - q1*q3),1-2*(q2*q2+q1*q1))) #yaw z = int(1500 + 637*math.asin(2*(q0*q3 + q1*q2))) #roll pos_command = "" # Anti-shaking if abs(self.xtemp-x)>1 or abs(self.ytemp-y)>1 or abs(self.ztemp-z)>1: pos_command = (str(x) + "," + str(y) + ","+str(z)+'\n') sys.stdout.flush() self.xtemp = x self.ytemp = y self.ztemp = z return pos_command
def troll(roll, dec, v2, v3): """ Computes the roll angle at the target position based on: the roll angle at the V1 axis(roll), the dec of the target(dec), and the V2/V3 position of the aperture (v2,v3) in arcseconds. Based on algorithm provided by Colin Cox and used in Generic Conversion at STScI. """ # Convert all angles to radians _roll = np.deg2rad(roll) _dec = np.deg2rad(dec) _v2 = np.deg2rad(v2 / 3600.) _v3 = np.deg2rad(v3 / 3600.) # compute components sin_rho = sqrt((pow(sin(_v2), 2) + pow(sin(_v3), 2)) - (pow(sin(_v2), 2) * pow(sin(_v3), 2))) rho = asin(sin_rho) beta = asin(sin(_v3) / sin_rho) if _v2 < 0: beta = pi - beta gamma = asin(sin(_v2) / sin_rho) if _v3 < 0: gamma = pi - gamma A = pi / 2. + _roll - beta B = atan2(sin(A) * cos(_dec), (sin(_dec) * sin_rho - cos(_dec) * cos(rho) * cos(A))) # compute final value troll = np.rad2deg(pi - (gamma + B)) return troll
def _FromXYZ(coord): x = coord[0] * 4 - 2 y = coord[1] * 4 - 2 z = coord[2] * 4 - 2 assert -2 <= x <= 2 assert -2 <= y <= 2 assert -2 <= z <= 2 r = GeoApi._GetDistance((0, 0, 0), (x, y, z)) if not r: return (0, 0, -GeoApi._EARTH_RADIUS) phi = math.asin(z / r) r_xy = r * math.cos(phi) if not r_xy: gamma = 0 else: gamma = math.asin(y / r_xy) if x < 0: if y > 0: gamma = math.pi - gamma else: gamma = -math.pi - gamma elevation = (r - 1) * GeoApi._EARTH_RADIUS phi = phi * 180.0 / math.pi gamma = gamma * 180.0 / math.pi return (phi, gamma, elevation)
def phase7(): print "Phase 7 - left knee bends" # acos(.5 z / l) targetAP = math.acos(.5 * 500 / 300) thetaAP = state.joint[ha.LAP].pos # change in x position of CoM during bend baseAR = math.asin(88.4/600) deltaAR = math.asin(88.4 / 400) - baseAR baseHP = state.joint[ha.LHP].pos elapsed = 0 while (elapsed < 10): s.get(state, wait=False, last=False) t1 = state.time thetaAP = filterTargetPos(targetAP, elapsed, freq) thetaAR = filterTargetPos(deltaAR, elapsed, freq) + baseAR # print elapsed, "\t", thetaAR # shift z ref.ref[ha.LHP] = -thetaAP + baseHP ref.ref[ha.LAP] = -thetaAP ref.ref[ha.LKN] = 2 * thetaAP # shift x ref.ref[ha.RHR] = -thetaAR ref.ref[ha.RAR] = thetaAR ref.ref[ha.LHR] = -thetaAR ref.ref[ha.LAR] = thetaAR r.put(ref) elapsed += TIME_STEP s.get(state, wait=False, last=False) t2 = state.time delay(TIME_STEP - (t2 - t1))
def getAngle(self,cc): r = ( (cc[2] - cc[0]) ** 2 + (cc[3] - cc[1] ) ** 2 ) ** 0.5 print('current R is:%8.4f' % r) print (cc) x = cc[2] - cc[0] y = cc[3] - cc[1] print(x,y) sina = y / r cosa = x / r starta = float() if y > 0 and x > 0: starta=math.asin ( sina ) ## 0 ~ PI/2 print ("q1: %f" % starta) else: if y > 0 and x <=0: starta = math.acos(cosa) ## PI/2 ~ PI print ("q2: %f" % starta) else: if y <=0 and x <=0: starta = math.pi*2 - math.acos(cosa) print("q3: %f" % starta) else: starta = math.pi * 2 + math.asin(sina) print("q4: %f" % starta) print("The angle of the hand is: %f" % starta) print('The coords of the hand are (after calculated from the Angle: is %s' % cc) return (starta)
def ApproximateTransitTime(t = float('nan'), P = float('nan'), RS = float('nan'), a = float('nan')): """Calculates the approximate transit time, using equation 2.6 in TE IN: t: transit duration, in s P: period of the planet, in s RS: radius of the host star, in m a: semi-major axis of the orbit, in m OUT: [t, P, RS, a]: list of all of the above """ #TODO: Extend this formula according to equation 3.4 in TE if(math.isnan(t)): t = P/math.pi * math.sin(RS/a) elif(math.isnan(P)): P = t * math.pi * math.sin(RS/a) elif(math.isnan(RS)): RS = a * math.asin(t*math.pi/P) elif(math.isnan(a)): a = RS / math.asin(t*math.pi/P) else: print ('TransitTime: WARNING: Nothing to solve') if(math.isnan(t) or math.isnan(P) or math.isnan(RS) or math.isnan(a)): print ('TransitTime: ERROR: Could not solve') return [t, P, RS, a]
def phase3(): print "Phase 3" targetAP = math.acos(.5 * 400 / 300) thetaAP = state.joint[ha.RAP].pos # change in x position of CoM during bend baseAR = math.asin(-88.4/600) deltaAR = math.asin(-88.4 / 400) - baseAR elapsed = 0 #print "AP start: ", thetaAP #print "AP target: ", targetAP while (elapsed < 10): s.get(state, wait=False, last=False) t1 = state.time thetaAP = filterTargetPos(targetAP, elapsed, freq) thetaAR = filterTargetPos(deltaAR, elapsed, freq) + baseAR # print elapsed, "\t", thetaAR # shift z ref.ref[ha.RHP] = -thetaAP ref.ref[ha.RAP] = -thetaAP ref.ref[ha.RKN] = 2 * thetaAP # shift x ref.ref[ha.RHR] = -thetaAR ref.ref[ha.RAR] = thetaAR ref.ref[ha.LHR] = -thetaAR ref.ref[ha.LAR] = thetaAR r.put(ref) elapsed += TIME_STEP s.get(state, wait=False, last=False) t2 = state.time delay(TIME_STEP - (t2 - t1))
def monitorArm(self, task): def clamp1(x): return min(1, max(-1, x)) direction = self.ralph.get_pos() - self.robotarm.get_pos() direction.z += 1 direction.normalize() # camera starts facing along x dec = math.asin(direction.x) cosdec = math.cos(dec) if cosdec > 1e-05: ra = math.asin(clamp1(direction.z / cosdec)) ra2 = math.acos(clamp1(direction.y / cosdec)) else: ra = ra2 = math.pi/2#float('nan') #print(cosdec, direction) #print(dec, ra, ra2, cosdec) if direction.z < 0: if ra2 < math.pi/2: ra2 = 0 else: ra2 = math.pi self.jointForearm.setH(-dec * 180/math.pi) self.jointBase.setP(ra2 * 180/math.pi) self.dirText.setText(str(direction)) self.anglesText.setText(str((dec, ra, ra2, cosdec))) a = self.jointForearm.getH() / 90.0 * 300 + 512 b = self.jointBase.getP() / 90.0 * 300 + 212 #print(a, b) baseID = 9 servos.setAngle({baseID:int(round(b)), (baseID+1):int(round(a))}) return task.again
def rpy(R): """Converts a rotation matrix to a roll,pitch,yaw angle triple. The result is given in radians.""" sign = lambda x: 1 if x > 0 else (-1 if x < 0 else 0) m = matrix(R) b = -math.asin(m[2][0]) # m(2,0)=-sb cb = math.cos(b) if abs(cb) > 1e-7: ca = m[0][0]/cb #m(0,0)=ca*cb ca = min(1.0,max(ca,-1.0)) if sign(m[1][0]) == sign(cb): #m(1,0)=sa*cb a = math.acos(ca); else: a = 2*math.pi - math.acos(ca) cc = m[2][2] / cb #m(2,2)=cb*cc cc = min(1.0,max(cc,-1.0)) if sign(m[2][1]) == sign(cb): #m(2,1)=cb*sc c = math.acos(cc) else: c = math.pi*2 - math.acos(cc) else: #b is close to 90 degrees, i.e. cb=0 #this reduces the degrees of freedom, so we can set c=0 c = 0 #m(0,1)=-sa a = -math.asin(m[0][1]); if sign(math.cos(a)) != sign(m[1][1]): #m(1,1)=ca a = math.pi - a; return c,b,a
def latlong_at_distaz(latE,longE,azimut,distance): from math import pi,sin,cos,asin """ Recherche des coordonnées d'un point en rapport avec un second : La fonction renvoi la latitude et la longitude du point cherché. La fonction connait la latitude et la longitude d'un point ainsi que la distance et l'azimut avec le point cherché. Usage (latS,lonS)=latlong(latE,longE,azimut,distance_km) """ R = 6371 # Rayon de la Terre (en km) d = 1.* distance/R # distance en radian sur la surface de la Terre azimut=azimut*pi/180.0 latE=latE*pi/180.0 longE=longE*pi/180.0 latS = asin(cos(d)*sin(latE)+sin(d)*cos(latE)*cos(azimut)) longS = longE + asin(sin(azimut)*sin(d)/cos(latS)) latS=latS*180.0/pi longS=longS*180.0/pi return (latS, longS)
def solar_intensity(lat = 40.713, lng = -74.006, date_time = datetime.datetime.now()): # day_of_year = datetime.datetime.strptime(date_time, '%m/%d/%Y').timetuple().tm_yday day_of_year = date_time.timetuple().tm_yday declination_angle = degrees(asin(sin(radians(23.45)) * sin(2 * pi/365 * (day_of_year - 81)))) # print 'declination_angle = ' + str(declination_angle) # ~~~equation of time~~~ to account for orbital eccentricity and axial wobble e_o_t = 9.87 * sin(2.0 * 2 * pi / 365 * (day_of_year - 81)) - 7.53 * cos(2 * pi / 365 * (day_of_year - 81)) - 1.5 * sin(2 * pi / 365 * (day_of_year - 81)) gmt_diff = floor(lng / 15) # hour difference from GMT (+5 for EST) lstm = 15.0 * gmt_diff # local standard time meridian (edge of time zone) tc = 4.0 * (lng - lstm) + e_o_t # time correction factor local_solar_time = date_time + datetime.timedelta(0, tc/60.0) lst_dec = local_solar_time.hour + local_solar_time.minute / 60.0 + local_solar_time.second / 3600.0 hour_angle = 15.0 * (lst_dec - 12.0) # print 'hour angle past solar noon = ' + str(hour_angle) # with a flat panel, the elevation angle is the incident angle elevation_angle = degrees(asin(sin(radians(declination_angle)) * sin(radians(lat)) + cos(radians(declination_angle)) * cos(radians(lat)) * cos(radians(hour_angle)))) # print elevation_angle rad_from_vert = pi / 2 - radians(elevation_angle) # zenith angle in radians for airmass formula if rad_from_vert < pi / 2: air_mass = 1 / (cos(rad_from_vert) + 0.50572 * (96.07995 - degrees(rad_from_vert)) ** (-1.6364)) else: air_mass = None e_0 = 1367 * (1 + 0.033 * cos(2 * pi * (day_of_year - 3) / 365)) if air_mass: intensity = cos(rad_from_vert) * e_0 * 0.7 ** (air_mass ** 0.678) return intensity else: return 0
def lensArea(self,circ): # First test if one is inside the other if self.containsCircle(circ) == True: return circ.area() if circ.containsCircle(self) == True: return self.area() # Second test if their is an intersection, if not, return 0 if self.intersects(circ) == False: return 0 # 1. Calculate the distance between the centers distX = abs(self.x - circ.x) distY = abs(self.y - circ.y) dist = pow(pow(distX,2) + pow(distY,2), .5) #print(dist) # 2. Derive angles theta and alpha. Angles formed by radii at points of itersection measured at center of circle theta = circ.radius/dist #print(theta) alpha = self.radius/dist #print(alpha) # 3. Get areas of each lens regions lensOne = (1/2)*pow(circ.radius,2)*(2*math.asin(alpha)-math.sin(2*math.asin(alpha))) lensTwo = (1/2)*pow(self.radius,2)*(2*math.asin(theta)-math.sin(2*math.asin(theta))) # Add areas together return lensOne + lensTwo
def orientation(self, x, y, z, magx, magy, magz): normalX = (x)/math.sqrt(x*x+y*y+z*z) normalY = (y)/math.sqrt(x*x+y*y+z*z) pitch = math.asin(-normalX) roll = math.asin(normalY/math.cos(pitch)) magxMax = 667 magxMin = -539 magyMax = 604 magyMin = -567 magzMax = 638 magzMin = -554 magxNormal = (magx-magxMin)/(magxMax-magxMin)*2-1 magyNormal = (magy-magyMin)/(magyMax-magyMin)*2-1 magzNormal = (magz-magzMin)/(magzMax-magzMin)*2-1 xheading = magxNormal*math.cos(pitch)+magzNormal*math.sin(pitch) yheading = magxNormal*math.sin(roll)*math.sin(pitch)+magyNormal*math.cos(roll)-magzNormal*math.sin(roll)*math.cos(pitch) zheading = -magxNormal*math.cos(roll)*math.sin(pitch) + magyNormal*math.sin(roll)+magzNormal*math.cos(roll)*math.cos(pitch) xheading = xheading*180/3.14159 yheading = yheading*180/3.14159 heading = 180*math.atan2(yheading, xheading)/(3.14159) if (yheading >= 0): return heading else: return (360 + heading)
def get_spherical_coords( self ): '''returns the spherical coordinates from a cartesian coordinates using this formula: - http://www.math.montana.edu/frankw/ccp/multiworld/multipleIVP/spherical/body.htm#converting :rtype: ( radius, zenith, azimuth ) ''' eye = self.target.camera.eye - self.target.camera.center radius = math.sqrt( pow(eye.x,2) + pow(eye.y,2) + pow(eye.z,2) ) s = math.sqrt( pow(eye.x,2) + pow(eye.y,2) ) if s == 0: s = 0.000000001 r = radius if r == 0: r = 0.000000001 angle_z = math.acos( eye.z / float(r) ) if eye.x < 0: angle_x = math.pi - math.asin( eye.y / s ) else: angle_x = math.asin( eye.y / s ) radius = radius / self.target.camera.get_z_eye() return radius, angle_z, angle_x
def extract_rot_trans(matrix): m = matrix.matrix t = Translation(Vector(m[0][2], m[1][2])) print m rot = [acos(m[0][0]), -asin(m[0][1]), asin(m[1][0]), acos(m[1][1])] print rot print t
def _determineBinAndBoutInFourAndFiveCirclesModes(self, hklNorm): """(Bin, Bout) = _determineBinAndBoutInFourAndFiveCirclesModes()""" BinModes = ('4cBin', '5cgBin', '5caBin') BoutModes = ('4cBout', '5cgBout', '5caBout') BeqModes = ('4cBeq', '5cgBeq', '5caBeq') azimuthModes = ('4cAzimuth') fixedBusingAndLeviWmodes = ('4cFixedw') # Calculate RHS of equation 20 # RHS (1/K)(S^-1*U*B*H)_3 where H/K = hklNorm UB = self._getUBMatrix() [SIGMA, TAU] = createVliegsSurfaceTransformationMatrices( self._getSigma() * TORAD, self._getTau() * TORAD) #S = SIGMA * TAU S = TAU * SIGMA RHS = (S.I * UB * hklNorm)[2, 0] if self._getMode().name in BinModes: Bin = self._getParameter('betain') check(Bin != None, "The parameter betain must be set for mode %s" % self._getMode().name) Bin = Bin * TORAD sinBout = RHS - sin(Bin) check(fabs(sinBout) <= 1, "Could not compute Bout") Bout = asin(sinBout) elif self._getMode().name in BoutModes: Bout = self._getParameter('betaout') check(Bout != None, "The parameter Bout must be set for mode %s" % self._getMode().name) Bout = Bout * TORAD sinBin = RHS - sin(Bout) check(fabs(sinBin) <= 1, "Could not compute Bin") Bin = asin(sinBin) elif self._getMode().name in BeqModes: sinBeq = RHS / 2 check(fabs(sinBeq) <= 1, "Could not compute Bin=Bout") Bin = Bout = asin(sinBeq) elif self._getMode().name in azimuthModes: azimuth = self._getParameter('azimuth') check(azimuth != None, "The parameter azimuth must be set for " "mode %s" % self._getMode().name) del azimuth # TODO: codeit raise NotImplementedError() elif self._getMode().name in fixedBusingAndLeviWmodes: bandlomega = self._getParameter('blw') check(bandlomega != None, "The parameter abandlomega must be set " "for mode %s" % self._getMode().name) del bandlomega # TODO: codeit raise NotImplementedError() else: raise RuntimeError("AngleCalculator does not know how to handle " "mode %s" % self._getMode().name) return (Bin, Bout)
def CountAngle(p1, p2, p3): l1 = GetLength(p1, p2) l2 = GetLength(p2, p3) if l1 * l2 < EPS: return 0 v1 = [p2[0] - p1[0], p2[1] - p1[1]] v2 = [p2[0] - p3[0], p2[1] - p3[1]] sin_arg = (v1[0] * v2[1] - v2[0] * v1[1]) / (l1 * l2) if abs(abs(sin_arg) - 1) < EPS: x = Sign(sin_arg) aSin = math.asin(x) else: aSin = math.asin(sin_arg) cos_arg = (v1[0] * v2[0] + v1[1] * v2[1]) / (l1 * l2) if abs(abs(cos_arg) - 1) < EPS: x = Sign(cos_arg) aCos = math.acos(x) else : aCos = math.acos(cos_arg) if sin_arg >= 0 and cos_arg >= 0: # first quarter return (aSin + aCos) / 2.0 elif sin_arg >= 0 and cos_arg < 0: # second quarter return ((PI - aSin) + aCos) / 2.0 elif sin_arg < 0 and cos_arg < 0: # third quarter return ((PI - aSin) + (2 * PI - aCos)) / 2.0 else: # fourth quarter return 2 * PI + (aSin - aCos) / 2.0
def _get_turbulent_cf(self,Rex): tol = 1.0e-8 r = 0.88 Te = 222.0 Mach = self.fc.Mach m = (self.gamma - 1.0)*Mach*Mach/2 TawTe = 1.0 + r*m F = self.TwTaw*TawTe Tw = F*Te A = (r*m/F)**0.5 B = (1.0+r*m-F)/F denom = (4*A*A + B**2)**0.5 alpha = (2.0*A*A-B)/denom beta = B / denom if Mach>0.1: Fc = r*m/((asin(alpha)+asin(beta))**2) else: Fc = ((1.0+F**0.5)/2)**2 xden = 1.0 + 122.0**(-5/Tw)/Te xnum = 1.0 + 122.0**(-5/Tw)/Tw Ftheta = xnum/xden * (1/F)**0.5 Fx = Ftheta / Fc RexBar = Fx * Rex Cfb = 0.074/(RexBar**0.2) itr = 0 err = tol+1.0 while err>tol and itr<100: Cf0 = Cfb xnum = 0.242 - Cfb**0.5*log10(RexBar*Cfb) xden = 0.121 + Cfb**0.5 / log(10.0) Cfb = Cfb*(1.0 + xnum/xden) err = abs(Cf0-Cfb) itr += 1 return Cfb/Fc
def check_fisher(self, path): # Будем делить пополам L = [] for line in open(path, "r"): line = line.split(" ") L.append(int(line[1])) eff = 0 noeff = 0 for i in range(59): eff += L[i] noeff += L[i + 59] eff = eff * 1500 / max(eff, noeff) noeff = noeff * 1500 / max(eff, noeff) sum_l = eff + noeff eff = noeff / float(eff + noeff) print "eff:", eff for name in sorted(self.S.keys()): eff_s = 0 noeff_s = 0 for i in range(59): eff_s += self.S[name][i] noeff_s += self.S[name][i + 59] eff_s = eff_s * 1500 / max(eff_s, noeff_s) noeff_s = noeff_s * 1500 / max(eff_s, noeff_s) sum_s = eff_s + noeff_s eff_s = noeff_s / float(eff_s + noeff_s) print "eff_s:", eff phi1 = asin(sqrt(eff / 100.0)) phi2 = asin(sqrt(eff_s / 100.0)) phi_emp = abs(phi1 - phi2) * sqrt(sum_l * sum_s / float(sum_s + sum_l)) print name, phi_emp print "____________________________"
def angulos(self): angles = [] angles.append(2 * asin(self.b / (2 * self.dist_centro_vertice))) angles.append(pi) angles.append(pi + 2 * asin(self.b / (2 * self.dist_centro_vertice))) angles.append(0) return angles
def p_tet_sp(angle_a, angle_ab, angle_ad, angle_cd): """ Returns an array with angles of interest (angle_b, angle_bc, angle_ac). Summer 2016. """ if (0 > angle_a) or (angle_a > 178) or (0 > angle_ab) or (angle_ab > 178) or (0 > angle_ad) or (angle_ad > 178) or \ (0 > angle_cd) or (angle_cd > 178): return exit('Does not exist 1') # Angles of the same triangle should be at least equal to 1 if angle_ad >= angle_ab: return exit('Does not exist 2') # Angle_ab = Angle_ad + Angle_bd if 0 < angle_ab - angle_ad < 180: angle_bd = angle_ab - angle_a else: return exit('Does not exist 3') angle_b = math.atan( (math.tan(math.radians(angle_a)) * math.tan(math.radians(angle_ad))) / math.tan(math.radians(angle_bd))) angle_bc = math.asin(math.cos(math.radians(angle_ad)) * math.sqrt( ((math.tan(math.radians(angle_ad)) ** 2) + (math.sin(math.radians(angle_cd)) ** 2)))) angle_ac = math.asin(math.cos(math.radians(angle_bd)) * math.sqrt( ((math.tan(math.radians(angle_bd)) ** 2) + (math.sin(math.radians(angle_cd)) ** 2)))) if 180 <= angle_a + angle_b: return exit('Does not exist 4') # Angle_a + Angle_b + Angle_c = 180 return [angle_b, angle_bc, angle_ac]
def _anglesToVirtualAngles(self, pos, wavelength): """ Return dictionary of all virtual angles in radians from VliegPosition object win radians and wavelength in Angstroms. The virtual angles are: Bin, Bout, azimuth and 2theta. """ # Create transformation matrices [ALPHA, DELTA, GAMMA, OMEGA, CHI, PHI] = createVliegMatrices( pos.alpha, pos.delta, pos.gamma, pos.omega, pos.chi, pos.phi) [SIGMA, TAU] = createVliegsSurfaceTransformationMatrices( self._getSigma() * TORAD, self._getTau() * TORAD) S = TAU * SIGMA y_vector = matrix([[0], [1], [0]]) # Calculate Bin from equation 15: surfacenormal_alpha = OMEGA * CHI * PHI * S * matrix([[0], [0], [1]]) incoming_alpha = ALPHA.I * y_vector minusSinBetaIn = dot3(surfacenormal_alpha, incoming_alpha) Bin = asin(bound(-minusSinBetaIn)) # Calculate Bout from equation 16: # surfacenormal_alpha has just ben calculated outgoing_alpha = DELTA * GAMMA * y_vector sinBetaOut = dot3(surfacenormal_alpha, outgoing_alpha) Bout = asin(bound(sinBetaOut)) # Calculate 2theta from equation 25: cosTwoTheta = dot3(ALPHA * DELTA * GAMMA * y_vector, y_vector) twotheta = acos(bound(cosTwoTheta)) psi = self._anglesToPsi(pos, wavelength) return {'Bin': Bin, 'Bout': Bout, 'azimuth': psi, '2theta': twotheta}
def __draw_cell(self, x, y, is_good, percent): # horrible graphic code,don't touch it unless you are very sure arc_coord = x - GroundView.CELL_RADIUS, y - GroundView.CELL_RADIUS, \ x + GroundView.CELL_RADIUS, y + GroundView.CELL_RADIUS delta_h = 2 * GroundView.CELL_RADIUS * abs(percent) - GroundView.CELL_RADIUS delta_x = sqrt(abs(GroundView.CELL_RADIUS * GroundView.CELL_RADIUS - delta_h * delta_h)) self.__canvas.create_oval(arc_coord, fill='white') if percent >= 0.1: if percent >= 0.99: self.__canvas.create_oval(arc_coord, fill='green', outline='black' if is_good else 'red') else: r = (int(510 - 510 * percent) if percent >= 0.5 else 255) * 16 * 16 * 16 * 16 g = int(255 if percent >= 0.5 else percent * 2 * 255) * 16 * 16 color = '#%06x' % (r + g) tri_coord = x - delta_x, y - delta_h, \ x + delta_x, y - delta_h, \ x, y self.__canvas.create_arc(arc_coord, start=degrees(asin(2 * percent - 1)), extent=-180 - 2 * degrees(asin(2 * percent - 1)), fill=color, outline=color) self.__canvas.create_polygon(tri_coord, fill=color if percent >= 0.5 else 'white', outline=color if percent >= 0.5 else 'white', width=1 if percent > 0.5 else 2) elif percent <= -0.1: if percent <= - 0.99: self.__canvas.create_oval(arc_coord, fill='grey', outline='black' if is_good else 'red') else: tri_coord = x - delta_x, y + delta_h, \ x + delta_x, y + delta_h, \ x, y self.__canvas.create_arc(arc_coord, start=-degrees(asin(2 * -percent - 1)), extent=180 + 2 * degrees(asin(2 * -percent - 1)), fill='grey', outline='grey') self.__canvas.create_polygon(tri_coord, fill='grey' if -percent >= 0.5 else 'white', outline='grey' if -percent >= 0.5 else 'white', width=1 if abs(percent) > 0.5 else 3) self.__canvas.create_oval(arc_coord, outline='black' if is_good else 'red')
def _determineBinAndBoutInZaxisModes(self, Hw3OverK): """(Bin, Bout) = _determineBinAndBoutInZaxisModes(HwOverK)""" BinModes = ('6czBin') BoutModes = ('6czBout') BeqModes = ('6czBeq') if self._getMode().name in BinModes: Bin = self._getParameter('betain') check(Bin != None, "The parameter betain must be set for mode %s" % self._getMode().name) Bin = Bin * TORAD # Equation 32a: Bout = asin(Hw3OverK - sin(Bin)) elif self._getMode().name in BoutModes: Bout = self._getParameter('betaout') check(Bout != None, "The parameter Bout must be set for mode %s" % self._getMode().name) Bout = Bout * TORAD # Equation 32b: Bin = asin(Hw3OverK - sin(Bout)) elif self._getMode().name in BeqModes: # Equation 32c: Bin = Bout = asin(Hw3OverK / 2) return (Bin, Bout)
def Iterate_emittances3HC_MW(twiss,param,phimain,Vmain,phiharm,Vharm,sigS,Curr,GT): #Definde differences i=1 time=0 diff1=1 diff2=1 diff3=1 diff4=1 difftot=diff1+diff2+diff3+diff4 #Calculate U0 U0=param['Cgamma']/(2*pi)*(param['En']/1e+9)**4*param['I2']*1e+9 #Calculate synchronous phase Phi_sync_nat=asin(U0/param['Vrf']) #Calculate damping partition numbers Jx=1-param['I4']/param['I2'] Jy=1 Jp=2+param['I4']/param['I2'] #print Jx,Jy,Jp # Caluclate damping times taux=(2*param['En']*param['C'])/(Jx*U0*param['cluz']) tauy=(2*param['En']*param['C'])/(Jy*U0*param['cluz']) taup=(2*param['En']*param['C'])/(Jp*U0*param['cluz']) #print taux,tauy,taup #Define step for iteration tt=taux/5 # Synchrotron tune Qs0=sqrt(param['ap']*param['hh']*sqrt(param['Vrf']**2-U0**2)/(2*pi*param['En'])) # Define the interpolation function for Microwave Instability microwave=interp2d(sigS,Curr,GT,kind='linear') #RF frequency w_rf =2*pi*(param['hh']*param['cluz']/param['C']-param['Detune0']) #Generator Frequency #Creates arrays for 3HC calculation posz=numpy.zeros(5000) perfil=numpy.zeros(5000) pot=numpy.zeros(5000) #Define longitudinal scale array posz=numpy.arange(0,5000.)/10-250 # in milimiters #Cretaes an array that's a subgroup of param inter={} inter['exi']=param['ex0'] inter['eyi']=(param['k_dw']+param['k_beta'])*param['ex0'] inter['spi']=param['sp0'] inter['gamma']=param['gamma'] inter['r0']=param['r0'] inter['Np']=param['Np'] inter['cluz']=param['cluz'] pot=1/(param['En']*param['C'])*param['cluz']/w_rf*(Vmain*1e3*(cos(Phi_sync_nat-phimain)-numpy.cos(posz/1000*w_rf/param['cluz']+Phi_sync_nat-phimain))+Vharm*1e3/param['mharm']*(cos(param['mharm']*pi-phiharm)-numpy.cos(param['mharm']*posz/1000*w_rf/param['cluz']+param['mharm']*pi-phiharm)))-1/(param['En']*param['C'])*U0*posz/1000 perfil=numpy.exp(-pot/(param['ap']*param['sp0']**2)) (pos0,sigma_mm)=calc_sigma(posz,perfil) inter['ssi']=sigma_mm/1000 while (difftot>10**(-7)): #Add the Microwave growth rate to the longitudinal plane DTp=microwave(sss,param['Np']) #print DTp (Tx,Ty,Tp)=Calc_Growth(twiss,inter) Tx=float(Tx)/param['C'] Ty=float(Ty)/param['C'] Tp=float(Tp)/param['C']+DTp exx=(-param['ex0']+exp(2*tt*(Tx-1/taux))*(param['ex0']+inter['exi']*(-1+Tx*taux)))/(-1+Tx*taux) eyy=(-(param['k_dw']*param['ex0']+param['k_beta']*exx*(1-tauy/Ty))+exp(2*tt*(Ty-1/tauy))*((param['k_dw']*param['ex0']+param['k_beta']*exx*(1-tauy/Ty))+inter['eyi']*(-1+Ty*tauy)))/(-1+Ty*tauy) spp=(-param['sp0']+exp(tt*(Tp-1/taup))*(param['sp0']+inter['spi']*(-1+Tp*taup)))/(-1+Tp*taup) #Calculate bunch length according to the RF potential (Main RF + 3HC) pot=1/(param['En']*param['C'])*param['cluz']/w_rf*(Vmain*1e3*(cos(Phi_sync_nat-phimain)-numpy.cos(posz/1000*w_rf/param['cluz']+Phi_sync_nat-phimain))+Vharm*1e3/param['mharm']*(cos(param['mharm']*pi-phiharm)-numpy.cos(param['mharm']*posz/1000*w_rf/param['cluz']+param['mharm']*pi-phiharm)))-1/(param['En']*param['C'])*U0*posz/1000 perfil=numpy.exp(-pot/(param['ap']*spp**2)) (pos0,sigma_mm)=calc_sigma(posz,perfil) sss=sigma_mm/1000 #print exx,eyy,spp,sss diff1=abs(exx-inter['exi'])/inter['exi'] diff2=abs(eyy-inter['eyi'])/inter['eyi'] diff3=abs(spp-inter['spi'])/inter['spi'] diff4=abs(sss-inter['ssi'])/inter['ssi'] difftot=diff1+diff2+diff3+diff4 #print difftot inter['exi']=exx; inter['eyi']=eyy; inter['spi']=spp; inter['ssi']=sss; time=i*tt; i=i+1 return (exx,eyy,spp,sss)
def vinc_dist(f, a, phi1, lembda1, phi2, lembda2): """ Returns the distance between two geographic points on the ellipsoid and the forward and reverse azimuths between these points. lats, longs and azimuths are in radians, distance in metres Returns ( s, alpha12, alpha21 ) as a tuple """ if (abs(phi2 - phi1) < 1e-8) and (abs(lembda2 - lembda1) < 1e-8): return 0.0, 0.0, 0.0 two_pi = 2.0 * math.pi piD4 = two_pi / 8.0 b = a * (1.0 - f) TanU1 = (1 - f) * math.tan(phi1) TanU2 = (1 - f) * math.tan(phi2) U1 = math.atan(TanU1) U2 = math.atan(TanU2) lembda = lembda2 - lembda1 last_lembda = -4000000.0 # an impossibe value omega = lembda # Iterate the following equations, # until there is no significant change in lembda while (last_lembda < -3000000.0 or lembda != 0 and abs( (last_lembda - lembda) / lembda) > 1.0e-9): sqr_sin_sigma = pow( math.cos(U2) * math.sin(lembda), 2) + \ pow( (math.cos(U1) * math.sin(U2) - \ math.sin(U1) * math.cos(U2) * math.cos(lembda) ), 2 ) Sin_sigma = math.sqrt(sqr_sin_sigma) Cos_sigma = math.sin(U1) * math.sin(U2) + math.cos(U1) * math.cos( U2) * math.cos(lembda) sigma = math.atan2(Sin_sigma, Cos_sigma) Sin_alpha = math.cos(U1) * math.cos(U2) * math.sin(lembda) / math.sin( sigma) alpha = math.asin(Sin_alpha) Cos2sigma_m = math.cos(sigma) - (2 * math.sin(U1) * math.sin(U2) / pow(math.cos(alpha), 2)) C = (f / 16) * pow(math.cos(alpha), 2) * (4 + f * (4 - 3 * pow(math.cos(alpha), 2))) last_lembda = lembda lembda = omega + (1-C) * f * math.sin(alpha) * (sigma + C * math.sin(sigma) * \ (Cos2sigma_m + C * math.cos(sigma) * (-1 + 2 * pow(Cos2sigma_m, 2) ))) u2 = pow(math.cos(alpha), 2) * (a * a - b * b) / (b * b) A = 1 + (u2 / 16384) * (4096 + u2 * (-768 + u2 * (320 - 175 * u2))) B = (u2 / 1024) * (256 + u2 * (-128 + u2 * (74 - 47 * u2))) delta_sigma = B * Sin_sigma * (Cos2sigma_m + (B/4) * \ (Cos_sigma * (-1 + 2 * pow(Cos2sigma_m, 2) ) - \ (B/6) * Cos2sigma_m * (-3 + 4 * sqr_sin_sigma) * \ (-3 + 4 * pow(Cos2sigma_m,2 ) ))) s = b * A * (sigma - delta_sigma) alpha12 = math.atan2( (math.cos(U2) * math.sin(lembda)), \ (math.cos(U1) * math.sin(U2) - math.sin(U1) * math.cos(U2) * math.cos(lembda))) alpha21 = math.atan2( (math.cos(U1) * math.sin(lembda)), \ (-math.sin(U1) * math.cos(U2) + math.cos(U1) * math.sin(U2) * math.cos(lembda))) if (alpha12 < 0.0): alpha12 = alpha12 + two_pi if (alpha12 > two_pi): alpha12 = alpha12 - two_pi alpha21 = alpha21 + two_pi / 2.0 if (alpha21 < 0.0): alpha21 = alpha21 + two_pi if (alpha21 > two_pi): alpha21 = alpha21 - two_pi return s, alpha12, alpha21
s3 = math.sin(math.radians(float(a3)))*float(s1)/math.sin(math.radians(float(a1))) if s2 != '' and s1 == '' and s3 == '': s1 = math.sin(math.radians(float(a1)))*float(s2)/math.sin(math.radians(float(a2))) s3 = math.sin(math.radians(float(a3)))*float(s2)/math.sin(math.radians(float(a2))) if s3 != '' and s1 == '' and s2 == '': s1 = math.sin(math.radians(float(a1)))*float(s3)/math.sin(math.radians(float(a3))) s2 = math.sin(math.radians(float(a2)))*float(s3)/math.sin(math.radians(float(a3))) #SAS if a1 != '' and a2 == '' and a3 == '' and s1 == '' and s2 != '' and s3 != '': s1 = round(math.sqrt(math.pow(float(s2),2)+math.pow(float(s3),2)-2*float(s2)*float(s3)*math.cos(math.radians(float(a1)))),2) if float(s2) > float(s3): a3 = round(math.degrees(math.asin(round(float(s3)*math.sin(math.radians(float(a1)))/float(s1),2))),2) a2 = 180 - float(a1) - float(a3) if float(s2) < float(s3): a2 = round(math.degrees(math.asin(round(float(s2)*math.sin(math.radians(float(a1)))/float(s1),2))),2) a3 = 180 - float(a1) - float(a2) if a2 != '' and s1 == '' and s3 == '' and s1 != '' and s3 != '' and s2 == '': s2 = math.sqrt(math.pow(float(s1),2)+math.pow(float(s3),2)-2*float(s1)*float(s3)*math.cos(math.radians(float(a2)))) if float(s1) > float(s3): a3 = round(math.degrees(math.asin(round(float(s3)*math.sin(math.radians(float(a2)))/float(s2),2))),2) a1 = 180 - float(a2) - float(a3) if float(s1) < float(s3): a1 = math.degrees(math.asin(float(s1)*math.sin(math.radians(float(a2)))/float(s2)))
def sms_reply(): global verified # Create a Cursor object to execute queries. # Initialize database db = init_db() # Get the message the user sent our Twilio number body = request.values.get('Body', None) body = body.lower() # Start our TwiML response phonenumber = request.values.get('From', None) cur = db.cursor() cur.execute( "SELECT ssn FROM patients.active_customers WHERE phone_number = " + phonenumber) #Get SSN SSN = cur.fetchone()[0] cur.execute( "SELECT usr_id FROM patients.active_customers WHERE phone_number = " + phonenumber) #Get usr_id usr_id = cur.fetchone()[0] # Get the message the user sent our Twilio number body = request.values.get('Body', None) body = body.lower() resp = MessagingResponse() # Determine the right reply for this message if body == 'refill prescription': cur.execute( "SELECT usrname FROM patients.active_customers WHERE phone_number = " + phonenumber) #Get usrname usrname = cur.fetchone()[0] resp.message( "Hello " + str(usrname) + ". Please enter the last 4 digits of your social security " "# and what prescription you need (#### drug_name)") elif len(body ) > 4 and body != 'refill prescription': #Confirm SSN is correct socialnum, prescript = body.split(" ") if (str(SSN) == socialnum): #Verifies SSN #Search for prescript cur.execute( "SELECT prescription_name FROM patients.prescription WHERE usr_id = " + str(usr_id)) #Get drug names prescript_list = cur.fetchmany() matches = (x for x in prescript_list if prescript == str(x)) if matches is None: resp.message("Not a valid prescription") quit() #toBeRefilled = matches[0] cur.execute("SELECT prescript_id FROM patients.prescription " "WHERE prescription_name = '" + str(prescript) + "'") #Get unique prescription ID prescript_id = cur.fetchone()[0] #prescript_id = 1 cur.execute("SELECT fill_left FROM patients.prescription " "WHERE prescript_id = " + str(prescript_id)) #Get numbers of fills left fill_left = cur.fetchone()[0] cur.execute("SELECT copay FROM patients.prescription " "WHERE prescript_id = " + str(prescript_id)) #Get copay copay = cur.fetchone()[0] cur.execute("SELECT last_fill FROM patients.prescription " "WHERE prescript_id = " + str(prescript_id)) #Get last fill date #last_fill = cur.fetchone()[0] today = datetime.datetime.now() #days_apart = (today-last_fill).days #Verify that the prescription can be filled #if(days_apart < 30): #resp.message("It has not been 30 days since your last refill") #quit() if (fill_left < 1): resp.message("No fills remaining") quit() cur.execute("SELECT address FROM patients.active_customers " "WHERE usr_id = '" + str(usr_id) + "'") #Get user address address = str(cur.fetchone()[0]) cur.execute("SELECT pharmacy FROM patients.active_customers " "WHERE usr_id = '" + str(usr_id) + "'") #Get pharmacy address pharm_address = str(cur.fetchone()[0]) else: resp.message("Not verified") quit() g = geocoder.google(str(pharm_address)) userloc2 = g.latlng h = geocoder.google(str(address)) pharm2 = h.latlng userloc2[1], userloc2[0], pharm2[1], pharm2[0] = map( radians, [userloc2[1], userloc2[0], pharm2[1], pharm2[0]]) dlon = pharm2[1] - userloc2[1] dlat = pharm2[0] - userloc2[0] a = sin( dlat / 2)**2 + cos(userloc2[0]) * cos(pharm2[0]) * sin(dlon / 2)**2 c = 2 * asin(sqrt(a)) k = 6371 #Use 3956 for milesw #print(dis) dis = c * k rated = 1.15 tme = dis / rated time = str(tme) resp.message("Thank you! Your refill of " + str(prescript) + " is on the way. " "Your copay of $" + str(copay) + " will be charged to your account.") resp.message("It will take approximately " + str(round(tme)) + " minutes for your refill to arrive.") # cur.execute("UPDATE patients.prescription SET last_fill = " + str(today) + ", " #"fill_left = " + str(fill_left-1) + " WHERE prescript_id = " + str(prescript_id)) return str(resp)
priority=1)) FUNCTIONS.append(Function(sign="tg", function=lambda x: fix_error(math.tan(x)), description="Тангенс угла в радианах (tg x, tg (pi / 4) = 1)", arguments=1, priority=1)) FUNCTIONS.append(Function(sign="ctg", function=lambda x: fix_error(1 / math.tan(x)), description="Косинус угла в радианах (ctg x, ctg (pi / 4) = 1)", arguments=1, priority=1)) FUNCTIONS.append(Function(sign="arcsin", function=lambda x: fix_error(math.asin(x)), description="Арксинус в радианах (arcsin x, arcsin 0.5 = 0.52...)", arguments=1, priority=1)) FUNCTIONS.append(Function(sign="arccos", function=lambda x: fix_error(math.acos(x)), description="Арккосинус в радианах (arccos x, arccos 0.5 = 1.04...)", arguments=1, priority=1)) FUNCTIONS.append(Function(sign="arctg", function=lambda x: fix_error(math.atan(x)), description="Тангенс угла в радианах (arctg x, arctg 0.5 = 0.46...)", arguments=1, priority=1))
import math RAD_TO_DEG = 57.295779513082320876798154814105 DEG_TO_RAD = 1 / RAD_TO_DEG while True: print("Yo give me some coordinates") elevation = float(input("elevation: ")) azimuth = float(input("azimuth: ")) elevation *= DEG_TO_RAD azimuth *= DEG_TO_RAD cartesian = [ math.sin(elevation) * math.cos(azimuth), math.sin(elevation) * math.sin(azimuth), math.cos(elevation) ] print(cartesian) theta = math.asin(-cartesian[1]) print(theta) print(cartesian[0] / math.cos(theta)) phi = math.asin(cartesian[0] / math.cos(theta)) print(phi) theta = theta * RAD_TO_DEG phi = phi * RAD_TO_DEG print("theta: {}\nphi: {}\n".format(theta, phi))
def almost_equal(actual, expected): return abs(actual - expected) < 0.00001 assert math.acos(0.57) == 0.9642904715818097 assert math.acos(1) == 0.0 assert math.acos(-1) == 3.141592653589793 assert math.acos(0) == 1.5707963267948966 assert math.acosh(45) == 4.499686190671499 assert math.acosh(30) == 4.0940666686320855 assert math.acosh(1) == 0.0 assert math.acosh(10) == 2.993222846126381 assert math.acosh(90) == 5.192925985263684 assert math.asin(0) == 0.0 assert math.asin(1) == 1.5707963267948966 assert math.asin(0.5) == 0.5235987755982989 assert math.asin(-1) == -1.5707963267948966 assert math.asinh(45) == 4.49993310426429 assert math.asinh(30) == 4.09462222433053 assert almost_equal(math.asinh(1), 0.881373587019543) assert math.asinh(10) == 2.99822295029797 assert math.asinh(90) == 5.192987713658941 assert math.atan(0) == 0.0 assert math.atan(1) == 0.7853981633974483 assert math.atan(0.5) == 0.4636476090008061 assert math.atan(-1) == -0.7853981633974483
def calculate_distance(lng1, lat1, lng2, lat2): # 经度和纬度 longitude and latitude,计算球上两点的距离 RADIUS = 6378.137 # 半径,单位km PI = math.pi return 2 * RADIUS * math.asin(math.sqrt(pow(math.sin(PI * (lat1 - lat2) / 360), 2) + math.cos(PI * lat1 / 180) * \ math.cos(PI * lat2 / 180) * pow(math.sin(PI * (lng1 - lng2) / 360), 2)))
print "Reading x,y and z-tilt value [degree] 10 times." for i in range(10): tx = 999 # Invalid tilt value. -127 <= tilt <= 128 ty = 999 tz = 999 if (not BrickPiUpdateValues()): if (BrickPi.Sensor[I2C_PORT] & (0x01 << I2C_DEVICE_INDEX)): tx = BrickPi.SensorI2CIn[I2C_PORT][I2C_DEVICE_INDEX][0] - 128 ty = BrickPi.SensorI2CIn[I2C_PORT][I2C_DEVICE_INDEX][1] - 128 tz = BrickPi.SensorI2CIn[I2C_PORT][I2C_DEVICE_INDEX][2] - 128 if (tx != 999): txd = math.degrees(math.asin(tx / 128.0)) if (ty != 999): tyd = math.degrees(math.asin(ty / 128.0)) if (tz != 999): tzd = math.degrees(math.asin(tz / 128.0)) print("tx: %d %3.2f ty: %d %3.2f tz: %d %3.2f" % (tx, txd, ty, tyd, tz, tzd)) time.sleep(1) # NOTE: The tilt reading is the angle of an axis with the horizontal # plane. It is stable but not very accurate. You will want to do a # 'null' reading before using it as a level. # Read the acceleration information from the sensor, ten times. BrickPi.SensorSettings[I2C_PORT][I2C_DEVICE_INDEX] = BIT_I2C_SAME BrickPi.SensorI2CWrite[I2C_PORT][I2C_DEVICE_INDEX] = 1
#!/usr/bin/python # -*- coding: utf-8 -*- import math # tüm sonuçları x değeri üzerinden hesaplayalım math.acos(x) # arccos'unu alır math.acosh(x) # hiperbolik arccos'unu alır math.asin(x) # arcsin'inini alır math.asinh(x) # hiperbolik arcsin'ini alır math.atan(x) # arctan'ını alır math.atan2(x, y) # x/y'nin tanjantını alır math.atanh(x) # hiperbolik arctan'ını alır math.ceil(x) # yuvarlar ve float cinsinden döndürür math.cos(x) # cosinüs'ünü alır math.cosh(x) # hiperbolik cosinüsünü alır math.degrees(x) # radyandan dereceye çevir math.exp(5) # e**x sonucunu döndürür math.fabs(x) # pozitif ve float türünde döndürür math.factorial(x) # faktoriyelini alır math.floor(x) # float sayıyı yuvarlayarak yine float türünden yazar 5.3->5.0 math.fmod(x, y) # y'ye göre modunu alır math.frexp(x) # x = m * 2.**a >> m float, a integer olacak ve sonuc (m, a) math.hypot(4, 2) # hipotenüs hesaplar math.ldexp(x, y) # x * (2**y) math.log( x, y ) # logaritma y tabanındaki sonucu y verilmesse taban 'e' sayısı olarak kabul edilir math.log10(x) # logaritma 10 tabanındaki sonucu math.log1p(x) # 1+x'in logaritma e tabanındaki sonucu math.modf(x) # modf(4.2)-> (0.2 , 4.0) sonucunu verir
def operate(operator, a, b): if operator == "+": result = a + b elif operator == '-': result = a - b elif operator == "*": result = a * b elif operator == "//": if b != 0: result = a // b else: print('ERROR: division by zero') exit(0) elif operator == "/": if b != 0: result = a / b else: print('ERROR: division by zero') exit(0) elif operator == "<=": result = a <= b elif operator == ">=": result = a >= b elif operator == "<": result = a < b elif operator == ">": result = a > b elif operator == "==": result = a == b elif operator == "!=": result = a != b elif operator == "%": result = a % b elif operator == "^": result = a**b elif operator == "abs": result = abs(a) elif operator == "round": result = round(a) elif operator == "cos": result = cos(a) elif operator == "acos": result = acos(a) elif operator == "sin": result = sin(a) elif operator == "asin": result = asin(a) elif operator == "tan": result = tan(a) elif operator == "atan": result = atan(a) elif operator == "log": result = log(a) elif operator == "log10": result = log10(a) elif operator == "sqrt": result = sqrt(a) elif operator == "exp": result = exp(a) elif operator == "!": result = factorial(a) else: print('ERROR: unknown math operator', operator) result = 0 if argsprint == 'y': if operator in oper: print('Operate:', a, operator, b, '=', result) elif operator in trfunc: print('Operate:', operator, a, '=', result) return result
def haversine(lon1, lat1, lon2, lat2): lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2]) dlon = lon2 - lon1 dlat = lat2 - lat1 a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2 return 2 * 6371 * asin(sqrt(a))
asin(x) 返回x的反正弦弧度值。 atan(x) 返回x的反正切弧度值。 atan2(y, x) 返回给定的 X 及 Y 坐标值的反正切值。 cos(x) 返回x的弧度的余弦值。 hypot(x, y) 返回欧几里德范数 sqrt(x*x + y*y)。 sin(x) 返回的x弧度的正弦值。 tan(x) 返回x弧度的正切值。 degrees(x) 将弧度转换为角度,如degrees(math.pi/2) , 返回90.0 radians(x) 将角度转换为弧度 ''' import math print("degrees(3) : ", math.degrees(3)) print("radians(-3) : ", math.radians(-3)) print("sin(3) : ", math.sin(3)) print("cos(3) : ", math.cos(3)) print("tan(3) : ", math.tan(3)) print("acos(0.64) : ", math.acos(0.64)) print("asin(0.64) : ", math.asin(0.64)) print("atan(0.64) : ", math.atan(0.64)) print("atan2(-0.50,-0.50) : ", math.atan2(-0.50, -0.50)) print("hypot(0, 2) : ", math.hypot(0, 2)) ''' Python数学常量: 常量 描述 pi 数学常量 pi(圆周率,一般以π来表示) e 数学常量 e,e即自然常数(自然常数)。 ''' print(math.pi) print(math.e)
def getPlots(graphRange, RPNStack, resolution): n = len(RPNStack) #Holds the current stack with which we solve for each x value. #This is a progressive stack, in that all final values are held here along #with the intermediate results of the current value of x stack = [] for k in range(0, n): stack.append([]) ax = graphRange["xMin"] #starting X value bx = graphRange["xMax"] #ending X value ay = graphRange["xMin"] #starting Y value by = graphRange["xMax"] #ending Y value stepx = math.fabs(ax - bx) / resolution #increment value in the X direction stepy = math.fabs(ay - by) / resolution #increment value in the Y direction i = 0 for d in properLoop(ay, by, stepy): stack[k].append([]) ax = graphRange["xMin"] #Reset these values for the next iteration bx = graphRange["xMax"] for e in properLoop(ax, bx, stepx): l = len(RPNStack[k]) for j in range(0, l): if (RPNStack[k][j].isdigit()): stack[k][i].append(RPNStack[k][j]) #Catch the independent elif (independentVar.find(RPNStack[k][j]) >= 0): if (RPNStack[k][j] == "x"): stack[k][i].append(ax) if (RPNStack[k][j] == "y"): stack[k][i].append(ay) #if the current token is an operator elif (operators.find(RPNStack[k][j]) >= 0): one = float(stack[k][i].pop()) two = float(stack[k][i].pop()) if (RPNStack[k][j] == "+"): stack[k][i].append(two + one) elif (RPNStack[k][j] == "-"): stack[k][i].append(two - one) elif (RPNStack[k][j] == "*"): stack[k][i].append(two * one) elif (RPNStack[k][j] == "/"): stack[k][i].append(two / one) elif (RPNStack[k][j] == "^"): stack[k][i].append(math.pow(two, one)) elif (RPNStack[k][j] in functionOperators): one = float(stack[k][i].pop()) if (RPNStack[k][j] == "sin"): stack[k][i].append(math.sin(one)) elif (RPNStack[k][j] == "cos"): stack[k][i].append(math.cos(one)) elif (RPNStack[k][j] == "tan"): stack[k][i].append(math.tan(one)) elif (RPNStack[k][j] == "arctan"): stack[k][i].append(math.atan(one)) elif (RPNStack[k][j] == "arcsin"): stack[k][i].append(math.asin(one)) if (RPNStack[k][j] == "arccos"): stack[k][i].append(math.acos(one)) #Increment our value at the current points ax += stepx ay += stepy i = i + 1 #print("parser", stack) return stack
def _sun_declination(self, juliancentury): e = self._obliquity_correction(juliancentury) lambd = self._sun_apparent_long(juliancentury) sint = sin(radians(e)) * sin(radians(lambd)) return degrees(asin(sint))
def get_msg_v_cmd(t): current_positon_x = position_msg.pose.position.x current_positon_y = position_msg.pose.position.y print(current_positon_x) print(position_msg) # Get the yaw from quaternions x = position_msg.pose.orientation.x y = position_msg.pose.orientation.y z = position_msg.pose.orientation.z w = position_msg.pose.orientation.w #t1 = +2.0 * (qua_w * qua_z + qua_x * qua_y) #t2 = +1.0 - 2.0 * (qua_y * qua_y + qua_z * qua_z) t0 = +2.0 * (w * x + y * z) t1 = +1.0 - 2.0 * (x * x + y * y) roll = math.atan2(t0, t1) t2 = +2.0 * (w * y - z * x) t2 = +1.0 if t2 > +1.0 else t2 t2 = -1.0 if t2 < -1.0 else t2 pitch = math.asin(t2) t3 = +2.0 * (w * z + x * y) t4 = +1.0 - 2.0 * (y * y + z * z) yaw = math.atan2(t3, t4) print(x) print(y) print(z) print(w) # Define a reference trajectory ref_x = math.sin(t) ref_y = math.cos(t) x_dot = math.cos(t) y_dot = -math.sin(t) ref_w = 1 ref_v = 1 ref_theta = math.atan2(y_dot, x_dot) x_error = ref_x - current_positon_x y_error = ref_y - current_positon_y theta_error = ref_theta - yaw error_x = (ref_x - current_positon_x) * math.cos(yaw) + ( ref_y - current_positon_y) * math.sin(yaw) error_y = -(ref_x - current_positon_x) * math.sin(yaw) + ( ref_y - current_positon_y) * math.cos(yaw) error_theta = theta_error c1 = 0.5 c2 = 10 c3 = 5 print('e_x=%f' % (x_error)) print('e_y=%f' % (y_error)) print('e_theta=%f' % (theta_error)) # Input control rule w = ref_w + 100 * ref_v * error_y * (math.sin(error_theta) / error_theta) + 0.5 * error_theta v = ref_v * math.cos(error_theta) + 0.4 * error_theta #w = ref_w + c2 * ref_v * (error_y*math.cos(error_theta/2)-error_x*math.sin(error_theta/2)) / math.sqrt(1+math.pow(error_x,2)+math.pow(error_y,2)) + c3 * math.sin(error_theta/2) #v = ref_v + c1 * error_x / math.sqrt(1 + math.pow(error_x,2) + math.pow(error_y,2)) # Publish the topic vel_msg = Twist() vel_msg.linear.x = 0.0 #abs(v) vel_msg.angular.z = 0.0 #abs(w) return vel_msg
def asin(ratio): return math.degrees(math.asin(ratio))
import unittest from math import radians, asin, degrees import cmath from ckmutil.ckm import * import numpy as np # some values close to the real ones Vus = 0.22 Vub = 3.5e-3 Vcb = 4.0e-2 gamma = radians(70.) # 70° in radians # converting to other parametrizations t12 = asin(Vus) t13 = asin(Vub) t23 = asin(Vcb) / cos(t13) delta = gamma laC = Vus A = sin(t23) / laC**2 rho_minus_i_eta = sin(t13) * cmath.exp(-1j * delta) / (A * laC**3) rho = rho_minus_i_eta.real eta = -rho_minus_i_eta.imag rhobar = rho * (1 - laC**2 / 2.) etabar = eta * (1 - laC**2 / 2.) class TestCKM(unittest.TestCase): v_s = ckm_standard(t12, t13, t23, delta) v_w = ckm_wolfenstein(laC, A, rhobar, etabar) v_t = ckm_tree(Vus, Vub, Vcb, gamma) v_wt = ckm_wolfenstein(*tree_to_wolfenstein(Vus, Vub, Vcb, gamma))
print "Random number", random.random() list = [2, 13, 133, 51, 'A'] random.shuffle(list) print "\nReshuffled list=", list random.shuffle(list) print "Reshuffled list=", list print "\nRandom Float uniform(2,14)=", random.uniform(2, 14) print "Random Float uniform(4,11)=", random.uniform(4, 11) #Math- Trigonometric functions '''22.Read the value x and y from the user and apply all trigonometric functions on these numbers. Note : Refer the tutorial Trigonometric operation table.''' import math x = float(input("Enter value of x")) y = float(input("Enter value of y")) print "acos(x)=", math.acos(x) print "asin(x)=", math.asin(x) print "atan(x)=", math.atan(x) print "atan2(y,x)=", math.atan2(y, x) print "cos(x)=", math.cos(x) print "hypot(x,y)=", math.hypot(x, y) print "sin(x)=", math.sin(x) print "tan(x)=", math.tan(x) print "degrees(x)=", math.degrees(x) print "radians(x)=", math.radians(x) #Math – math.pi application '''23.Find the area of Circle given that radius of a circle. ( Use pi value from Math module)''' import math radius = int(input("Enter value of radius")) area = math.pi * radius * radius print "The area of circle is", area, "sqmeters"
def onCreate(self, state): AppCompatActivity.onCreate(self, state) self.setContentView(R.layout.activity_graph_output) sharedpreferences = MainActivity.sharedpreferences AoA = sharedpreferences.getInt("AoA", 5) * math.pi / 180. Arch = sharedpreferences.getInt("Arch", 2) TE = sharedpreferences.getInt("TE", 15) Mux = (50. - sharedpreferences.getInt("Mux", 45)) / -100. # Plotting parameters windowSize = 1 quiverResolution = 0.05 contourResolution = 0.01 nContours = 25 # Geometric parameters chord = 1 teAngle = TE * math.pi / 180 arch = Arch * math.pi / 180 mux = Mux # Should be in negative x direction # Derived parameters k = 2. - (teAngle / math.pi) muy = arch * k r = 1. b = (1. - (muy)**2)**(1. / 2.) + mux # Normalize inputs with respect to chord chordNorm = 2. * k * b / (1. - (1. - (b / math.cos(arch)))**k) b = b * chord / chordNorm r = r * chord / chordNorm mux = mux * chord / chordNorm muy = muy * chord / chordNorm mu = complex(mux, muy) # Flow parameters Vfs = 2 circulation = -4. * math.pi * Vfs * r * math.sin(AoA + math.asin(muy / r)) #l = -997*Vfs*circulation #cl = 2*l/(997*Vfs*Vfs) # Method to transform circle into airfoil def transformZ(Z, k, b): z = k * b * ((Z + b)**k + (Z - b)**k) / ((Z + b)**k - (Z - b)**k) return z # Method to obtain the velocity field around a circle def circleVelField(Vfs, AoA, circulation, Z, mu, r): first = complex(Vfs * math.cos(-AoA), Vfs * math.sin(-AoA)) second = complex(0, circulation) / (2. * math.pi * (Z - mu)) third = complex(Vfs * r**2 * math.cos(AoA), Vfs * r**2 * math.sin(AoA)) / (Z - mu)**2 return (first - second - third) # Method to obtain the derivative of the transform with respect to the original # plane def derivativeZ(Z, k, b): dz = 4. * k**2 * b**2 * (Z + b)**(k - 1.) * (Z - b)**(k - 1.) / ( (Z + b)**k - (Z - b)**k)**2 if dz == 0: dz = 1 return dz # Method to obtain pressure coefficients from velocities def cp(velZ, Vfs): cp = 1. - (abs(velZ)**2 / Vfs**2) return cp # Method for inverse transformm from z-plane into original def inverseZ(z, k, b): # Find kappa kappa = 1. / k Z = -b * (1. + ((z + (k * b)) / (z - (k * b)))**kappa) / (1. - ((z + (k * b)) / (z - (k * b)))**kappa) return (Z) # Checks if a point is inside the original circle def pointInCircle(Z, mu, r): inside = False if ( abs(Z - mu) < r * 0.98 ): # 0.98 to mask just inside the circle to aviod whitespace at the edge of the foil inside = True return inside # Run main xFoil = [] yFoil = [] xVel = [] yVel = [] xCp = [] yCp = [] for theta in range(0, 360): X = r * math.cos(theta * math.pi / 180) + mux Y = r * math.sin(theta * math.pi / 180) + muy Z = complex(X, Y) transform = transformZ(Z, k, b) xFoil.append(transform.real) yFoil.append(transform.imag) velZ = circleVelField(Vfs, AoA, circulation, Z, mu, r) / derivativeZ(Z, k, b) velX = velZ.real velY = -velZ.imag xVel.append(velX) yVel.append(velY) c = cp(velZ, Vfs) xCp.append(transform.real) yCp.append(c) X = [] Y = [] U = [] V = [] for y in range(int(-windowSize / quiverResolution), int(1 + (windowSize / quiverResolution))): Ui = [] Vi = [] X.append(y * quiverResolution) Y.append(y * quiverResolution) for x in range(int(-windowSize / quiverResolution), int(1 + (windowSize / quiverResolution))): z = complex(x * quiverResolution, y * quiverResolution) Z = inverseZ(z, k, b) velZ = circleVelField(Vfs, AoA, circulation, Z, mu, r) / derivativeZ(Z, k, b) velX = velZ.real velY = -velZ.imag if (pointInCircle(Z, mu, r)): Ui.append(0) Vi.append(0) else: Ui.append(velX) Vi.append(velY) U.append(Ui) V.append(Vi) X1 = [] Y1 = [] CP = [] for y in range(int(-windowSize / contourResolution), int(1 + (windowSize / contourResolution))): CPi = [] X1.append(y * contourResolution) Y1.append(y * contourResolution) for x in range(int(-windowSize / contourResolution), int(1 + (windowSize / contourResolution))): z = complex(x * contourResolution, y * contourResolution) Z = inverseZ(z, k, b) velZ = circleVelField(Vfs, AoA, circulation, Z, mu, r) / derivativeZ(Z, k, b) velX = velZ.real velY = -velZ.imag if (pointInCircle(Z, mu, r)): CPi.append(1) #NaN else: CPi.append(cp(velZ, Vfs)) CP.append(CPi) # Figure 1 fig = plt.figure() ax = fig.add_subplot(111) CS = ax.contourf(X1, Y1, CP, nContours, cmap=plt.cm.jet) cbar = fig.colorbar(CS) cbar.ax.set_ylabel('Pressure Coefficient') q = ax.quiver(X, Y, U, V, units='width', width=0.001) ax.quiverkey(q, X=0.3, Y=1.05, U=5, label='Velocity vector', labelpos='E') ax.fill(xFoil, yFoil, color='g') ax.set_aspect('equal', 'datalim') ax.set_xlabel('Real Axis') ax.set_ylabel('Imaginary Axis') root = Environment.getExternalStorageDirectory() plt.savefig(root.getAbsolutePath() + "/fig1.png") bitmap = BitmapFactory.decodeFile(root.getAbsolutePath() + "/fig1.png") self.findViewById(R.id.imageView).setImageBitmap(bitmap)
def dipole_tilt_angle(t): """credit: Eelco Doornbos""" return asin(np.dot(sun_unit_vector(t), pole_unit_vector(t)))
def calc_color_element_rates(color): """(WIP) 色成分比を求めます""" upper_bound = max(color[0], color[1], color[2]) lower_bound = min(color[0], color[1], color[2]) variable_height = upper_bound - lower_bound rank2_color = (color[0] - lower_bound, color[1] - lower_bound, color[2] - lower_bound) # RBGの比は求まった color_rates = (rank2_color[0] / variable_height, rank2_color[1] / variable_height, rank2_color[2] / variable_height) # 弧度法に変換 color_degrees = (color_rates[0] * 360, color_rates[1] * 360, color_rates[2] * 360) # その結果、 0, x, 360 に分別できる3値が返ってくる。ここで x は 0 <= x <= 360。 # まず 360 が 2つあるものを除外します。 if color_degrees[0] == 360 and color_degrees[1] == 360: # イエロー return color_rates, 60 # 12時が0°の時計回り if color_degrees[1] == 360 and color_degrees[2] == 360: # シアン return color_rates, 180 if color_degrees[0] == 360 and color_degrees[2] == 360: # マゼンタ return color_rates, 300 # 0 が2つあるものを除外します。 if color_degrees[1] == 0 and color_degrees[2] == 0: # 赤 return color_rates, 0 if color_degrees[0] == 0 and color_degrees[2] == 0: # 緑 return color_rates, 120 if color_degrees[0] == 0 and color_degrees[1] == 0: # 青 return color_rates, 240 # これで、 0, x, 360 に分別できる3値が返ってくる。ここで x は 0 < x < 360。 x_rate = sorted(color_rates)[1] # print(f"x_rate={x_rate}") # 0 と 360 がどこにあるかで、オレンジ相、黄緑相、エメラルドグリーン相、 # ドジャースブルー相、インディゴ相、クリムゾン相 の6つに分けれる。 # また、 x は、 オレンジ相では昇順、黄緑相では降順になるなど、交互になる。 if color_degrees[0] == 360 and color_degrees[2] == 0: # オレンジ相 (0°~60°) では、 x は上昇緑 return color_rates, math.asin(x_rate) if color_degrees[1] == 360 and color_degrees[2] == 0: # 黄緑相 (60°~120°) では、 x は下降赤 return color_rates, math.asin(x_rate) if color_degrees[0] == 0 and color_degrees[1] == 360: # エメラルドグリーン相 (120°~180°) では、 x は上昇青 return color_rates, math.asin(x_rate) if color_degrees[0] == 0 and color_degrees[2] == 360: # ドジャースブルー相 (180°~240°) では、 x は下降緑 return color_rates, math.asin(x_rate) if color_degrees[1] == 0 and color_degrees[2] == 360: # インディゴ相 (240°~300°) では、 x は上昇赤 return color_rates, math.asin(x_rate) if color_degrees[0] == 360 and color_degrees[1] == 0: # クリムゾン相 (300°~360°) では、 x は下降青 return color_rates, math.asin(x_rate) expected_theta = sorted(color_rates)[1] # # 元が cos(theta) だったので、acos(theta) したらどうか? # colors_theta = ( # math.acos(color_rates[0]), # math.acos(color_rates[1]), # math.acos(color_rates[2])) # # 緑は -120°、 青は 120° 足しているから、逆に引いたらどうか # colors_theta = ( # colors_theta[0], # colors_theta[1] + math.radians(120), # colors_theta[2] - math.radians(120), # ) return color_rates, expected_theta
def calcphi2vec(v1, v2): return math.degrees( math.asin( np.linalg.norm(np.cross(v1, v2)) / np.linalg.norm(v1) / np.linalg.norm(v2)))
def L_join(self, wall, target, idx , target_idx): """ Compute given wall angles to corner join target wall, mind that when calling this method, the 2 walls already have a coincident end point (achieved by the extend method). / wall / / / . / / / angle / /_wi__/______.__________________________ / / ./ . / ti / c. / . / / . /ti . target.Width / / . / . /____ /_____/_____ _____._____ _____ _____ _____ __ / ./ wi / target / . / / / . / / / .w_angle / /.____/_____/___________________________________________ """ # TODO: correct the bug of two different size walls with big angle in between print("--------\n"+"L_Join "+wall.Name+"_"+str(idx) + " with " +target.Name+"_"+str(target_idx) + "\n") if idx == 0: w1 = wall.Proxy.get_first_point(wall) w2 = wall.Proxy.get_last_point(wall) elif idx == 1: w1 = wall.Proxy.get_last_point(wall) w2 = wall.Proxy.get_first_point(wall) if target_idx == 0: t1 = target.Proxy.get_first_point(target) t2 = target.Proxy.get_last_point(target) elif target_idx == 1: t1 = target.Proxy.get_last_point(target) t2 = target.Proxy.get_first_point(target) angle = Draft.DraftVecUtils.angle(w2-w1,t2-t1) # print("angle between walls: " + str(math.degrees(angle)) + "\n") if angle > 0: w_i = wall.Width * math.cos(math.pi/2-angle) t_i = target.Width * math.cos(math.pi/2-angle) if angle < 0: w_i = wall.Width * math.cos(-math.pi/2-angle) t_i = target.Width * math.cos(-math.pi/2-angle) c = math.sqrt( w_i**2 + t_i**2 - 2 * abs(w_i) * t_i * math.cos(math.pi-angle) ) w_angle = math.asin( w_i / c * math.sin(math.pi-angle)) # print("Parameters:\n") # print("w_i: " + str(w_i) + "\n") # print("c: " + str(c) + "\n") # print("flipping parameter: " + str(c) + "\n") # print("cut angle: " + str(math.degrees(w_angle)) + "\n") # assign the angles to the correct wall end w_angle = math.degrees( w_angle ) if idx == 0: wall.FirstCoreInnerAngle = w_angle wall.FirstCoreOuterAngle = -w_angle wall.FirstCoreOffset = 0.0 elif idx == 1: wall.LastCoreInnerAngle = -w_angle wall.LastCoreOuterAngle = +w_angle wall.LastCoreOffset = 0.0
def asind(x): rad = math.asin(x) return math.degrees(rad)
def __init__(self, placelat, ascmc2, lon, lat, ra, decl): #transform #0-90: x = x #90-180: 180-x = 180-x (before the trigon. calc. subtract x from 180.0 and at the end of the calc the result should be subtr. from 180.0) #180-270: x-180 = x+180 (before the trigon. calc. subtract 180.0 from x and at the end of the calc the result should be added to 180.0) #270-360: 360-x = 360-x #sin(delta) = sin(long)*sin(obl) #sin(ar) = ctg(obl)*tg(delta) or tg(ar) = cos(obl)*/ctg(long) #cos(war) = cos(long)*cos(beta)/cos(delta) #sin(A.D.)(FI or placelat)[ascensio-differentia] = tg(FI)*tg(delta) #SemiArcus #dsa = 90.0+A.D. #nsa = 90.0-A.D. #MeridianDistance: #Diurnal planet: |wRA-ARMC| (wahre = real) #Nocturnal planet : |wRA-ARIC| #HD(HorizonDistance) #TH(TemporalHour) = SA/6 semiarcus is either diurnal or nocturnal dependig on the planet #HOD(HourlyDistance)=MD/TH #PMP (Placidus Mundane Position) #if QuadrantI: pmp = 90.0-90.0*MD/SA #if QuadrantII: pmp = 90.0+90.0*MD/SA #if QuadrantIII: pmp = 270.0-90.0*MD/SA #if QuadrantIV: pmp = 270.0+90.0*MD/SA #A.D.(fi or poleheight) = MD*AD(FI)/SA #Poleheight(fi): tg(fi) = sin(AD(fi))/tg(delta) #A.O. D.O.: #AO: Eastern planet: AO = AR-AD #DO: western planet: DO = AR+AD #sa, adlat, md, hd, adph, ph, ao/do #the sign (positive or negative) is used in the Positions-table (e.g. if SA is positive then a 'D' will indicate that it is diurnal) ramc = ascmc2[houses.Houses.MC][houses.Houses.RA] raic = ramc + 180.0 if raic > 360.0: raic -= 360.0 self.eastern = True if ramc > raic: if ra > raic and ra < ramc: self.eastern = False else: if (ra > raic and ra < 360.0) or (ra < ramc and ra > 0.0): self.eastern = False #adlat adlat = 0.0 self.valid = True val = math.tan(math.radians(placelat)) * math.tan(math.radians(decl)) if math.fabs(val) <= 1.0: adlat = math.degrees(math.asin(val)) self.valid = False #md med = math.fabs(ramc - ra) if med > 180.0: med = 360.0 - med icd = math.fabs(raic - ra) if icd > 180.0: icd = 360.0 - icd md = med #hd aoasc = ramc + 90.0 if aoasc >= 360.0: aoasc -= 360.0 dodesc = raic + 90.0 if dodesc >= 360.0: dodesc -= 360.0 aohd = ra - adlat hdasc = aohd - aoasc if hdasc < 0.0: hdasc *= -1 if hdasc > 180.0: hdasc = 360.0 - hdasc dohd = ra + adlat hddesc = dohd - dodesc if hddesc < 0.0: hddesc *= -1 if hddesc > 180.0: hddesc = 360.0 - hddesc hd = hdasc if hddesc < hdasc: hd = hddesc hd *= -1 #sa (southern hemisphere!?) dsa = 90.0 + adlat nsa = 90.0 - adlat self.abovehorizon = True if med > dsa: self.abovehorizon = False sa = dsa if not self.abovehorizon: sa = -nsa #nocturnal if negative md = icd md *= -1 #TH(TemporalHour) th = sa / 6.0 #HOD(HourlyDistance) hod = 0.0 if th != 0.0: hod = md / math.fabs(th) #pmp pmp = 0.0 tmd = md if tmd < 0.0: tmd *= -1 pmpsa = sa if pmpsa < 0.0: pmpsa *= -1 if not self.abovehorizon and self.eastern: pmp = 90.0 - 90.0 * (tmd / pmpsa) elif not self.abovehorizon and not self.eastern: pmp = 90.0 + 90.0 * (tmd / pmpsa) elif self.abovehorizon and not self.eastern: pmp = 270.0 - 90.0 * (tmd / pmpsa) elif self.abovehorizon and self.eastern: pmp = 270.0 + 90.0 * (tmd / pmpsa) #adphi tval = math.fabs(sa) adphi = 0.0 if tval != 0.0: adphi = math.fabs(tmd) * adlat / tval #phi tval = math.tan(math.radians(decl)) phi = 0.0 if tval != 0.0: phi = math.degrees(math.atan(math.sin(math.radians(adphi)) / tval)) #ao/do (southern hemisphere!?) if self.eastern: ao = ra - adphi else: ao = ra + adphi ao *= -1 #do if negative self.speculum = (lon, lat, ra, decl, adlat, sa, md, hd, th, hod, pmp, adphi, phi, ao)
def sunrise_sunset(latitude, longitude, d, t=0.5, timezone=0): dateOrdinal = d.toordinal() - 734124 + 40529 # Julian Day and Century calculations julianDay = dateOrdinal + 2415018.5 + t - timezone / 24 julianCentury = (julianDay - 2451545) / 36525 # Detailed calculation # Inspired by: http://www.esrl.noaa.gov/gmd/grad/solcalc/calcdetails.html geomMeanLongSun = 280.46646 + julianCentury * ( 36000.76983 + julianCentury * 0.0003032) % 360 geomMeanAnomSun = 357.52911 + julianCentury * (35999.05029 - 0.0001537 * julianCentury) eccentEarthOrbit = 0.016708634 - julianCentury * ( 0.000042037 + 0.0000001267 * julianCentury) sunEqOfCtr = sin(radians(geomMeanAnomSun)) * ( 1.914602 - julianCentury * (0.004817 + 0.000014 * julianCentury)) + sin( radians(2 * geomMeanAnomSun)) * ( 0.019993 - 0.000101 * julianCentury) + sin( radians(3 * geomMeanAnomSun)) * 0.000289 sunTrueLong = geomMeanLongSun + sunEqOfCtr sunAppLong = sunTrueLong - 0.00569 - 0.00478 * sin( radians(125.04 - 1934.136 * julianCentury)) meanObliqEcliptic = 23 + (26 + ( (21.448 - julianCentury * (46.815 + julianCentury * (0.00059 - julianCentury * 0.001813)))) / 60) / 60 obliqCorr = meanObliqEcliptic + 0.00256 * cos( radians(125.04 - 1934.136 * julianCentury)) sunDeclination = degrees( asin(sin(radians(obliqCorr)) * sin(radians(sunAppLong)))) varY = tan(radians(obliqCorr / 2)) * tan(radians(obliqCorr / 2)) eqOfTime = 4 * degrees( varY * sin(2 * radians(geomMeanLongSun)) - 2 * eccentEarthOrbit * sin(radians(geomMeanAnomSun)) + 4 * eccentEarthOrbit * varY * sin(radians(geomMeanAnomSun)) * cos(2 * radians(geomMeanLongSun)) - 0.5 * varY * varY * sin(4 * radians(geomMeanLongSun)) - 1.25 * eccentEarthOrbit * eccentEarthOrbit * sin(2 * radians(geomMeanAnomSun))) hourAngleSunrise = degrees( acos( cos(radians(90.833)) / (cos(radians(latitude)) * cos(radians(sunDeclination))) - tan(radians(latitude)) * tan(radians(sunDeclination)))) #sunset and sunrise final calculations solarNoon = (720 - 4 * longitude - eqOfTime + timezone * 60) / 1440 sunriseTime = (solarNoon - hourAngleSunrise * 4 / 1440 ) #edge case under/over 0/1 sunsetTime = (solarNoon + hourAngleSunrise * 4 / 1440 ) #edge case under/over 0/1 #solar azimuth calculations (solar azimuth is degrees CW from North) trueSolarTime = ((t * 1440) + eqOfTime + (4 * longitude) - (60 * timezone)) % 1440 if trueSolarTime / 4 < 0: hourAngle = trueSolarTime / 4 + 180 else: hourAngle = trueSolarTime / 4 - 180 solarZenithAngle = degrees( acos( sin(radians(latitude)) * sin(radians(sunDeclination)) + cos(radians(latitude)) * cos(radians(sunDeclination)) * cos(radians(hourAngle)))) if hourAngle > 0: solarAzimuthAngle = (degrees( acos(((sin(radians(latitude)) * cos(radians(solarZenithAngle))) - sin(radians(sunDeclination))) / (cos(radians(latitude)) * sin(radians(solarZenithAngle))))) + 180) % 360 else: solarAzimuthAngle = (540 - degrees( acos(((sin(radians(latitude)) * cos(radians(solarZenithAngle))) - sin(radians(sunDeclination))) / (cos(radians(latitude)) * sin(radians(solarZenithAngle))))) ) % 360 # Solar azimuth calculation (at sunrise) solarZenithAngleSunrise = degrees( acos( sin(radians(latitude)) * sin(radians(sunDeclination)) + cos(radians(latitude)) * cos(radians(sunDeclination)) * cos(radians(hourAngleSunrise)))) # Solar Zenith Angle is approximately the same at sunrise and sunset, so use it for both azimuth calculations solarAzimuthAngleSunrise = (540 - degrees( acos( ((sin(radians(latitude)) * cos(radians(solarZenithAngleSunrise))) - sin(radians(sunDeclination))) / (cos(radians(latitude)) * sin(radians(solarZenithAngleSunrise))))) ) % 360 solarAzimuthAngleSunset = (degrees( acos( ((sin(radians(latitude)) * cos(radians(solarZenithAngleSunrise))) - sin(radians(sunDeclination))) / (cos(radians(latitude)) * sin(radians(solarZenithAngleSunrise))))) + 180) % 360 # Sunrise and sunset may be on different UTC days sunriseDate = d sunsetDate = d # If not using timezones, there is the possibility for returning < 0:00, > 24:00 if sunriseTime < 0: sunriseDate -= timedelta(days=1) elif sunriseTime > 1: sunriseDate += timedelta(days=1) sunriseTime = sunriseTime % 1 if sunsetTime < 0: sunsetDate -= timedelta(days=1) elif sunsetTime > 1: sunsetDate += timedelta(days=1) sunsetTime = sunsetTime % 1 # Sunset time calculation sunsetHour = int(24.0 * sunsetTime) sunsetMinute = int((24.0 * sunsetTime - sunsetHour) * 60) sunsetSecond = int( ((24.0 * sunsetTime - sunsetHour) * 60 - sunsetMinute) * 60) sunsetHMS = time(sunsetHour, sunsetMinute, sunsetSecond) #sunset = str(sunsetHour).zfill(2)+":"+str(sunsetMinute).zfill(2)+":"+str(sunsetSecond).zfill(2) # Sunrise time calculation sunriseHour = int(24.0 * sunriseTime) sunriseMinute = int((24.0 * sunriseTime - sunriseHour) * 60) sunriseSecond = int( ((24.0 * sunriseTime - sunriseHour) * 60 - sunriseMinute) * 60) sunriseHMS = time(sunriseHour, sunriseMinute, sunriseSecond) #sunrise = str(sunriseHour).zfill(2)+":"+str(sunriseMinute).zfill(2)+":"+str(sunriseSecond).zfill(2) # Combine time and date into a datetime object sunset = datetime.combine(sunsetDate, sunsetHMS) sunrise = datetime.combine(sunriseDate, sunriseHMS) # Formatting output #sunset = str(sunsetHour).zfill(2)+":"+str(sunsetMinute).zfill(2)+":"+str(sunsetSecond).zfill(2) #sunrise = str(sunriseHour).zfill(2)+":"+str(sunriseMinute).zfill(2)+":"+str(sunriseSecond).zfill(2) #return output dictionary return { "sunrise": { "datetime": sunrise, "solarazimuth": solarAzimuthAngleSunrise }, "sunset": { "datetime": sunset, "solarazimuth": solarAzimuthAngleSunset } }
def quart_to_rpy(x, y, z, w): r = math.atan2(2 * (w * x + y * z), 1 - 2 * (x * x + y * y)) p = math.asin(2 * (w * y - z * x)) y = math.atan2(2 * (w * z + x * y), 1 - 2 * (z * z + y * y)) return y
c = 299792458 #빛의 속도 h = 6.62607004 * (10**-34) #플랑크 상수 #산란각 및 입사광의 파장입력 inci = float(input("입사광의 파장 :")) theta = float(input("산란각 :")) theta = math.pi * (theta / 180) #라디안으로 변환 #수식 #scat - inci = (h/(m*c))*(1-math.cos(theta)) scat = inci + (h / (m * c)) * (1 - math.cos(theta)) #산란광 파장 계산 print('산란파 파장:' + str(scat)) #산란파 파장 출력 pi = math.asin(h * math.sin(theta) / (m * c * scat)) #전자 튕기는 각 구현 #######컴프턴 산란 그래픽 구현####### plt.rc('font', family='Malgun Gothic') x = np.linspace(-10, 10, 100) y1 = np.sin(x / (inci * 10**11)) #입사광 그래프 구현 y2 = np.sin(x / (scat * 10**11)) #산란파 그래프 구현 plt.plot(x, y1, label='입사광') plt.plot(x, y2, label='산란파') plt.show() vp_inci = sphere(pos=vec(0, 0, 0), make_trail=True, radius=0.0002, color=color.red) vp_radi = sphere(pos=vec(5, 0, 0), make_trail=True, radius=0.08)
def run(self): print "" print "-----------------------------------------" print "State: \033[1;33m" + str(self.name) + "\033[0m" print "-----------------------------------------" print "Roundabout distance: ", self.globals.roundabout.getDistance() print "Branking Distance: ", self.globals.getBrakingDistance() print "MyCar Speed: ", self.globals.speed mypos = self.globals.car.getPosition() * 10 line_segments = self.globals.parser.scenario.getLineSegments(mypos) print "Roadname: ", line_segments[-1][0].parent.parent.name for seg in line_segments: print "Roadname: ", seg[0].parent.parent.name # calculate intersection positions for lane in self.globals.roundabout.lanes: intersection_position = self.globals.roundabout.getPosition() alpha = math.atan2(intersection_position[0], -intersection_position[1]) - (math.pi / 2) intersection_position[0] -= lane.r b = self.globals.norm(self.globals.roundabout.getPosition()) a = lane.r if -1 <= ((math.sin(alpha) * b) / a) <= 1: beta = math.pi - math.asin( (math.sin(alpha) * b) / a) # mehrere loesungen!!!!! SSW Dreieck gamma = math.pi - alpha - beta d = (a * math.sin(gamma)) / math.sin(alpha) lane.debug.setPosition([d, 0, 0.02], self.globals.car_handle) intersection_position = np.array([d, 0, 0]) else: # print "intersection_position far away.." intersection_position = None lane.intersection_position = intersection_position # line_segments = self.globals.parser.scenario.getLineSegments(intersection_position * 10) # for segment in line_segments: # lane.lineSegment = segment[0] # lane.posInLineSegment = segment[1] self.globals.target_speed = self.globals.max_speed self.brake = None enemys = self.globals.getEnemysInRange(4) #enemys = self.globals.enemys if self.globals.roundabout.getDistance( ) - 1 < self.globals.car_length / 2: print "\033[1;33m------------------------------State_Change----------------------------------\033[0m" self.globals.currentState = States.AdaptiveCruiseControl( self.globals) return for enemy in enemys: # reset dynamic paramters # enemy.lane = None # ---------------------- assign enemy to lane and estimatespeed -------------------- enemy.mapToLane() # if enemy.lane is not None: # enemy.estimateSpeed() # enemy.mapToLineSegment() enemy.printStats() # print "lineSegment: ", enemy.lineSegment # print "lane: ", enemy.lane # if enemy.lineSegment is not None: # print "Road: ",enemy.lineSegment[0].parent.parent.name # print "LaneID: ",enemy.lineSegment[0].parent.id # # # if enemy.lineSegment is not None and enemy.lane is not None and enemy.lane.lineSegment is not None and enemy.lineSegment[0] is not None: # if enemy.lane.lineSegment.parent == enemy.lineSegment[0].parent: # print "lineSegment: ", enemy.lineSegment[0] # print "lane: ", enemy.lane.lineSegment # print "enemy_distance: ", self.globals.parser.scenario.getDistance(enemy.lineSegment[0],enemy.lane.lineSegment) # else: # print "comparing unequal lanes!--------------------------------------------------------------------------------------------" intersection_distance = enemy.getIntersectionDistance() print "intersection_distance: ", intersection_distance if enemy.lane is not None: lane_dist = self.globals.roundabout.getDistance( ) - enemy.lane.outer_r brake_dist = self.globals.getBrakingDistance( ) + self.globals.car_length + 0.2 if lane_dist <= brake_dist and enemy.speed != 0 and intersection_distance is not None: if intersection_distance > 0: enemy_timewindow = abs(intersection_distance / enemy.speed) deltav = self.globals.max_speed - self.globals.speed t = deltav / self.globals.accel s = 0 if enemy_timewindow - t < 0: s = ( self.globals.accel / 2 ) * enemy_timewindow * enemy_timewindow + self.globals.speed * enemy_timewindow else: s = ( (self.globals.accel / 2) * t * t + self.globals.speed * t ) + (enemy_timewindow - t) * self.globals.max_speed goal_distance = enemy.lane.intersection_position[ 0] + self.globals.car_length stop_distance = self.globals.roundabout.getDistance( ) - enemy.lane.outer_r - self.globals.car_length print "Goal distance: ", goal_distance print "Stop distance: ", stop_distance print "Estimated Car distance: ", s print "Estimated Time Window: ", enemy_timewindow if s < goal_distance and s > stop_distance: print "Stop Caused my: ", enemy.name self.setBrakeDistance( self.globals.roundabout.getDistance() - enemy.lane.outer_r - self.globals.car_length / 2 - 0.1) if self.brake is not None: print "\033[1;33m------------------------------State_Change----------------------------------\033[0m" self.globals.currentState = States.Brake( self.globals, self.brake, ToRoundabout(self.globals)) self.globals.currentState.run()