Python math.degrees() Examples

The following are code examples for showing how to use math.degrees(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
Project: astrobase   Author: waqasbhatti   File: coordutils.py    (MIT License) View Source Project 7 votes vote down vote up
def decimal_to_dms(decimal_value):
    '''
    This converts from decimal degrees to DD:MM:SS, returned as a tuple.

    '''

    if decimal_value < 0:
        negative = True
        dec_val = fabs(decimal_value)
    else:
        negative = False
        dec_val = decimal_value

    degrees = trunc(dec_val)
    minutes_deg = dec_val - degrees

    minutes_mm = minutes_deg * 60.0
    minutes_out = trunc(minutes_mm)
    seconds = (minutes_mm - minutes_out)*60.0

    if negative:
        degrees = degrees
        return '-', degrees, minutes_out, seconds
    else:
        return '+', degrees, minutes_out, seconds 
Example 2
Project: coa_tools   Author: ndee85   File: export_json.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def get_bone_rotation(self,bone):
        pose_bone = self.armature.pose.bones[bone.name]
        
        if bone.parent != None:
            local_mat = self.get_bone_transformation(bone.parent).inverted() * self.get_bone_transformation(bone)
        else:
            local_mat = self.get_bone_transformation(bone)    
        bone_euler_rot = local_mat.decompose()[1].to_euler()
        
        degrees = round(math.degrees(bone_euler_rot.y),2)
        return -math.radians(degrees) 
Example 3
Project: astrobase   Author: waqasbhatti   File: coordutils.py    (MIT License) View Source Project 6 votes vote down vote up
def angle_wrap(angle,radians=False):
    '''
    Wraps the input angle to 360.0 degrees.

    if radians is True: input is assumed to be in radians, output is also in
    radians

    '''

    if radians:
        wrapped = angle % (2.0*PI)
        if wrapped < 0.0:
            wrapped = 2.0*PI + wrapped

    else:

        wrapped = angle % 360.0
        if wrapped < 0.0:
            wrapped = 360.0 + wrapped

    return wrapped 
Example 4
Project: astrobase   Author: waqasbhatti   File: coordutils.py    (MIT License) View Source Project 6 votes vote down vote up
def dms_to_decimal(sign, degrees, minutes, seconds):
    '''
    Converts from DD:MM:SS to a decimal value. Returns decimal degrees.

    '''

    dec_deg = fabs(degrees) + fabs(minutes)/60.0 + fabs(seconds)/3600.0

    if sign == '-':
        return -dec_deg
    else:
        return dec_deg


############################
## DISTANCE AND XMATCHING ##
############################ 
Example 5
Project: mav_rtk_gps   Author: ethz-asl   File: bearing_from_mag.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 6 votes vote down vote up
def mitsuta_mean(self, angles_array):
        # Function meant to work with degrees, covert inputs
        # from radians to degrees and output from degrees to radians
        D = math.degrees(angles_array[0])
        mysum = D
        for val in angles_array[1:]:
            val = math.degrees(val)
            delta = val - D
            if delta < -180.0:
                D = D + delta + 360.0
            elif delta < 180.0:
                D = D + delta
            else:
                D = D + delta - 360.0
            mysum = mysum + D
        m = mysum / len(angles_array)

        avg = math.radians((m + 360.0) % 360.0)
        # make sure avg is between -pi and pi
        if avg > math.pi:
            avg = avg - 2.0 * math.pi
        elif avg < -math.pi:
            avg = avg + 2.0 * math.pi

        return avg 
Example 6
Project: qgis-shapetools-plugin   Author: NationalSecurityAgency   File: geomath.py    (GNU General Public License v2.0) View Source Project 6 votes vote down vote up
def atan2d(y, x):
    """compute atan2(y, x) with the result in degrees"""

    if abs(y) > abs(x):
      q = 2; x, y = y, x
    else:
      q = 0
    if x < 0:
      q += 1; x = -x
    ang = math.degrees(math.atan2(y, x))
    if q == 1:
      ang = (180 if y >= 0 else -180) - ang
    elif q == 2:
      ang =  90 - ang
    elif q == 3:
      ang = -90 + ang
    return ang 
Example 7
Project: qgis-shapetools-plugin   Author: NationalSecurityAgency   File: geodesic.py    (GNU General Public License v2.0) View Source Project 6 votes vote down vote up
def Line(self, lat1, lon1, azi1,
           caps = GeodesicCapability.STANDARD |
           GeodesicCapability.DISTANCE_IN):
    """Return a GeodesicLine object

    :param lat1: latitude of the first point in degrees
    :param lon1: longitude of the first point in degrees
    :param azi1: azimuth at the first point in degrees
    :param caps: the :ref:`capabilities <outmask>`
    :return: a :class:`~geographiclib.geodesicline.GeodesicLine`

    This allows points along a geodesic starting at (*lat1*, *lon1*),
    with azimuth *azi1* to be found.  The default value of *caps* is
    STANDARD | DISTANCE_IN, allowing direct geodesic problem to be
    solved.

    """

    from geographiclib.geodesicline import GeodesicLine
    return GeodesicLine(self, lat1, lon1, azi1, caps) 
Example 8
Project: qgis-shapetools-plugin   Author: NationalSecurityAgency   File: geodesic.py    (GNU General Public License v2.0) View Source Project 6 votes vote down vote up
def DirectLine(self, lat1, lon1, azi1, s12,
                 caps = GeodesicCapability.STANDARD |
                 GeodesicCapability.DISTANCE_IN):
    """Define a GeodesicLine object in terms of the direct geodesic
    problem specified in terms of spherical arc length

    :param lat1: latitude of the first point in degrees
    :param lon1: longitude of the first point in degrees
    :param azi1: azimuth at the first point in degrees
    :param s12: the distance from the first point to the second in
      meters
    :param caps: the :ref:`capabilities <outmask>`
    :return: a :class:`~geographiclib.geodesicline.GeodesicLine`

    This function sets point 3 of the GeodesicLine to correspond to
    point 2 of the direct geodesic problem.  The default value of *caps*
    is STANDARD | DISTANCE_IN, allowing direct geodesic problem to be
    solved.

    """

    return self._GenDirectLine(lat1, lon1, azi1, False, s12, caps) 
Example 9
Project: qgis-shapetools-plugin   Author: NationalSecurityAgency   File: geodesic.py    (GNU General Public License v2.0) View Source Project 6 votes vote down vote up
def ArcDirectLine(self, lat1, lon1, azi1, a12,
                 caps = GeodesicCapability.STANDARD |
                 GeodesicCapability.DISTANCE_IN):
    """Define a GeodesicLine object in terms of the direct geodesic
    problem specified in terms of spherical arc length

    :param lat1: latitude of the first point in degrees
    :param lon1: longitude of the first point in degrees
    :param azi1: azimuth at the first point in degrees
    :param a12: spherical arc length from the first point to the second
      in degrees
    :param caps: the :ref:`capabilities <outmask>`
    :return: a :class:`~geographiclib.geodesicline.GeodesicLine`

    This function sets point 3 of the GeodesicLine to correspond to
    point 2 of the direct geodesic problem.  The default value of *caps*
    is STANDARD | DISTANCE_IN, allowing direct geodesic problem to be
    solved.

    """

    return self._GenDirectLine(lat1, lon1, azi1, True, a12, caps) 
Example 10
Project: qgis-shapetools-plugin   Author: NationalSecurityAgency   File: LatLon.py    (GNU General Public License v2.0) View Source Project 6 votes vote down vote up
def parseDMSStringSingle(str):
        '''Parse a single coordinate either DMS or decimal degrees.
        It simply returns the value but doesn't maintain any knowledge
        as to whether it is latitude or longitude'''
        str = str.strip().upper()
        try:
            if re.search("[NSEW\xb0]", str) == None:
                coord = float(str)
            else:
                m = re.findall('(.+)\s*([NSEW])', str)
                if len(m) != 1 or len(m[0]) != 2:
                    raise ValueError('Invalid DMS Coordinate')
                coord = LatLon.parseDMS(m[0][0], m[0][1])
        except:
            raise ValueError('Invalid Coordinates')
        return coord 
Example 11
Project: CPNSimulatorGui   Author: chris-kuhr   File: ArcItem.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def setPolygon(self):
        '''Calculate position and rotation of the arc arrow head.'''
        rotDeg = 0            
        xlength = self.pos1.x() - self.pos2.x()
        ylength = self.pos1.y() - self.pos2.y()
        d = math.sqrt( math.pow( xlength , 2) + math.pow( ylength , 2) )        
        if d > 0:
            beta = math.acos( xlength / d )
            rotDeg = math.degrees( beta ) 
        
        self.arrowPolygonObject.setPolygon( QtGui.QPolygonF( [
                                                 QtCore.QPointF( (self.pos2.x() -10),  (self.pos2.y() +5)), 
                                                 QtCore.QPointF( (self.pos2.x() -10) , (self.pos2.y() -5)), 
                                                 QtCore.QPointF(       self.pos2.x() ,      self.pos2.y())
                                                 ] ) ) 
        
        self.arrowPolygonObject.setBrush( QtGui.QBrush(QtCore.Qt.black) )
        
        """ self.angle()!!!!!!!!!"""
#         self.arcLinePolygon.angle()
#         self.arcLinePolygon.rotate(rotDeg)
#         self.arcLinePolygon.setPos( self.pos2 ) 

    #------------------------------------------------------------------------------------------------ 
Example 12
Project: CPNSimulatorGui   Author: chris-kuhr   File: ArrowGui.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def setPolygon(self):
        rotDeg = 0            
        xlength = self.pos1.x() - self.pos2.x()
        ylength = self.pos1.y() - self.pos2.y()
        d = math.sqrt( math.pow( xlength , 2) + math.pow( ylength , 2) )        
        if d > 0:
            beta = math.acos( xlength / d )
            rotDeg = math.degrees( beta ) 
        
        self.arcLinePolygon.setPolygon( QtGui.QPolygonF( [
                                                 QtCore.QPointF( (self.pos2.x() -10),  (self.pos2.y() +5)), 
                                                 QtCore.QPointF( (self.pos2.x() -10) , (self.pos2.y() -5)), 
                                                 QtCore.QPointF(       self.pos2.x() ,      self.pos2.y())
                                                 ] ) ) 
        
        self.arcLinePolygon.setBrush( QtGui.QBrush(QtCore.Qt.black) )
        
        """ self.angle()!!!!!!!!!"""
#         self.arcLinePolygon.angle()
#         self.arcLinePolygon.rotate(rotDeg)
#         self.arcLinePolygon.setPos( self.pos2 ) 
    #------------------------------------------------------------------------------------------------ 
Example 13
Project: pyrsss   Author: butala   File: iaga2002.py    (MIT License) View Source Project 6 votes vote down vote up
def iaga2df(iaga2002_fname, D_to_radians=True):
    """
    Parser the magnetometer data record stored in the IAGA-2002 format
    file *iaga2002_fname*. If *D_to_radians*, declination data (D) are
    converted from degrees to radians. Return the tuple with the
    :class:`DataFrame` containing the data and header information
    """
    with open(iaga2002_fname) as fid:
        # parse header
        header, cols = parse_header(fid)
        keys = ['B_' + x for x in cols]
        # parse data
        index = []
        data_map = defaultdict(list)
        for line in fid:
            toks = line.split()
            dt = datetime.strptime(toks[0] + ' ' + toks[1], '%Y-%m-%d %H:%M:%S.%f')
            index.append(dt)
            data = map(convert_float, toks[3:])
            for key_i, data_i in zip(keys, data):
                if key_i == 'B_D' and D_to_radians:
                    data_i = math.radians(data_i)
                data_map[key_i].append(data_i)
    df = PD.DataFrame(index=index, data=data_map)
    return df, header 
Example 14
Project: pypilot   Author: pypilot   File: calibration_fit.py    (license) View Source Project 6 votes vote down vote up
def ComputeDeviation(points, fit):
    m, d  = 0, 0
    for p in points:
        v = vector.sub(p[:3], fit[:3])
        m += (1 - vector.dot(v, v) / fit[3]**2)**2

        if len(fit) > 4:
            n = vector.dot(v, p[3:]) / vector.norm(v)
            if abs(n) <= 1:
                ang = math.degrees(math.asin(n))
                d += (fit[4] - ang)**2
            else:
                d += 1e111
    m /= len(points)
    d /= len(points)
    return [m**.5, d**.5] 
Example 15
Project: satellite-tracker   Author: lofaldli   File: coords.py    (MIT License) View Source Project 6 votes vote down vote up
def eci_to_latlon(pos, phi_0=0):
    (x, y, z) = pos
    rg = (x*x + y*y + z*z)**0.5
    z = z/rg
    if abs(z) > 1.0:
        z = int(z)

    lat = degrees(asin(z))
    lon = degrees(atan2(y, x)-phi_0)
    if lon > 180:
        lon -= 360
    elif lon < -180:
        lon += 360
    assert -90 <= lat <= 90
    assert -180 <= lon <= 180
    return lat, lon 
Example 16
Project: UPBGE-CommunityAddon   Author: elmeunick9   File: MotionBlur.py    (license) View Source Project 6 votes vote down vote up
def update(self):
		from bge import logic as G
		import math

		scene = G.getCurrentScene()
		own = self.own

		cam = scene.active_camera
		wtc = cam.world_to_camera

		own['rota'] = math.degrees(cam.localOrientation.to_euler().x)

		if 'init' not in own:
			set = cam.projection_matrix * wtc
			own['prev'] = set
			own['init'] = True
			self = MotionBlur
		set = (cam.projection_matrix * wtc)
		cameraMatrix = own['prev']
		
		self.x = cameraMatrix
		self.viewProjectionInverse = set.inverted()

		own['prev'] = set 
Example 17
Project: enigma2   Author: OpenLD   File: rotor_calc.py    (license) View Source Project 6 votes vote down vote up
def calcAzimuth(SatLon, SiteLat, SiteLon, Height_over_ocean = 0):

	def rev(number):
		return number - math.floor(number / 360.0) * 360

	sinRadSiteLat = math.sin(math.radians(SiteLat))
	cosRadSiteLat = math.cos(math.radians(SiteLat))

	Rstation = r_eq / (math.sqrt(1 - f * (2 - f) * sinRadSiteLat **2))
	Ra = (Rstation + Height_over_ocean) * cosRadSiteLat
	Rz = Rstation * (1 - f) ** 2 * sinRadSiteLat

	alfa_rx = r_sat * math.cos(math.radians(SatLon - SiteLon)) - Ra
	alfa_ry = r_sat * math.sin(math.radians(SatLon - SiteLon))
	alfa_rz = -Rz

	alfa_r_north = -alfa_rx * sinRadSiteLat + alfa_rz * cosRadSiteLat

	if alfa_r_north < 0:
		Azimuth = 180 + math.degrees(math.atan(alfa_ry / alfa_r_north))
	elif alfa_r_north > 0:
		Azimuth = rev(360 + math.degrees(math.atan(alfa_ry / alfa_r_north)))
	else:
		Azimuth = 0
	return Azimuth 
Example 18
Project: enigma2   Author: OpenLD   File: rotor_calc.py    (license) View Source Project 6 votes vote down vote up
def calcSatHourangle(SatLon, SiteLat, SiteLon):
	Azimuth = calcAzimuth(SatLon, SiteLat, SiteLon )
	Elevation = calcElevation(SatLon, SiteLat, SiteLon)

	a = - math.cos(math.radians(Elevation)) * math.sin(math.radians(Azimuth))
	b = math.sin(math.radians(Elevation)) * math.cos(math.radians(SiteLat)) - \
		math.cos(math.radians(Elevation)) * math.sin(math.radians(SiteLat)) * \
		math.cos(math.radians(Azimuth))

	# Works for all azimuths (northern & southern hemisphere)
	returnvalue = 180 + math.degrees(math.atan(a / b))

	if Azimuth > 270:
		returnvalue += 180
		if returnvalue > 360:
			returnvalue = 720 - returnvalue

	if Azimuth < 90:
		returnvalue = 180 - returnvalue

	return returnvalue 
Example 19
Project: CodeDay-Pong-AI   Author: ianjury   File: pong.py    (license) View Source Project 6 votes vote down vote up
def getStatistics(circle_x, circle_y, bar1_x, bar1_y, bar2_x, bar2_y):
    out = [0, 0, 0]
    midX = GLOBAL_WIDTH / 2
    midY = GLOBAL_HEIGHT / 2
    dx = midX - circle_x
    dy = midY - circle_y
    rads = atan2(-dy, dx)
    rads %= 2*pi
    angle = degrees(rads)
    if  (bar1_x - circle_x)**2 != 0:
        p1Distance = sqrt((bar1_y - circle_y)**2 / (bar1_x - circle_x)**2)
    if (bar2_x - circle_x)**2 != 0:
        p2Distance = sqrt((bar2_y - circle_y)**2 / (bar2_x - circle_x)**2)
    out[0] = angle
    out[1] = p1Distance
    out[2] = p2Distance
    return out

#determines how to move padel based on neural net input 
Example 20
Project: AboveTustin   Author: kevinabrandon   File: geomath.py    (license) View Source Project 6 votes vote down vote up
def distance(pointA, pointB):
	"""
	Calculate the great circle distance between two points 
	on the earth (specified in decimal degrees)

	http://stackoverflow.com/questions/15736995/how-can-i-quickly-estimate-the-distance-between-two-latitude-longitude-points
	"""
	# convert decimal degrees to radians 
	lon1, lat1, lon2, lat2 = map(math.radians, [pointA[1], pointA[0], pointB[1], pointB[0]])

	# haversine formula 
	dlon = lon2 - lon1 
	dlat = lat2 - lat1 
	a = math.sin(dlat/2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon/2)**2
	c = 2 * math.asin(math.sqrt(a)) 
	r = 3956  # Radius of earth in miles. Use 6371 for kilometers
	return c * r 
Example 21
Project: CC3501-2017-1   Author: ppizarror   File: utils_math.py    (license) View Source Project 6 votes vote down vote up
def xyz_to_spr(x, y, z):
    """Convierte las coordenadas cartesianas (x,y,z) a las coordenadas esfericas (r,phi,theta) con angulos en grados"""
    # Calculo el radio
    r = math.sqrt(x ** 2 + y ** 2 + z ** 2)
    # Calculo el angulo theta
    if z > 0:
        theta = math.atan(math.sqrt(x ** 2 + y ** 2) / z)
    elif z == 0:
        theta = math.pi / 2
    else:
        theta = math.pi + math.atan(math.sqrt(x ** 2 + y ** 2) / z)
    # Calculo el angulo phi
    if x > 0:
        if y > 0:
            phi = math.atan(y / x)
        else:
            phi = 2 * math.pi + math.atan(y / x)
    elif x == 0:
        phi = sgn(y) * math.pi / 2
    else:
        phi = math.pi + math.atan(y / x)
    theta = math.degrees(theta)
    phi = math.degrees(phi) % 360
    theta = min(max(theta, 0.000001), 180)
    return r, phi, theta 
Example 22
Project: CC3501-2017-1   Author: ppizarror   File: utils.py    (license) View Source Project 6 votes vote down vote up
def xyz_to_spr(x, y, z):
    """Convierte las coordenadas cartesianas (x,y,z) a las coordenadas esfericas (r,phi,theta) con angulos en grados"""
    # Calculo el radio
    r = math.sqrt(x ** 2 + y ** 2 + z ** 2)
    # Calculo el angulo theta
    if z > 0:
        theta = math.atan(math.sqrt(x ** 2 + y ** 2) / z)
    elif z == 0:
        theta = math.pi / 2
    else:
        theta = math.pi + math.atan(math.sqrt(x ** 2 + y ** 2) / z)
    # Calculo el angulo phi
    if x > 0:
        if y > 0:
            phi = math.atan(y / x)
        else:
            phi = 2 * math.pi + math.atan(y / x)
    elif x == 0:
        phi = sgn(y) * math.pi / 2
    else:
        phi = math.pi + math.atan(y / x)
    theta = math.degrees(theta)
    phi = math.degrees(phi) % 360
    theta = min(max(theta, 0.000001), 180)
    return r, phi, theta 
Example 23
Project: codecad   Author: bluecube   File: cube_thingie.py    (license) View Source Project 6 votes vote down vote up
def cube_with_base(unit_cube):
    """ Take a unit cube and turn it into a statue thingie, standing on one corner """
    m = cube_side / 2

    prepared_cube = unit_cube.scaled(cube_side) \
        .rotated_x(45) \
        .rotated_y(math.degrees(math.acos(math.sqrt(2/3)))) \
        .translated(0, 0, cube_side * math.sqrt(3) / 2 + base_height)

    bottom = rectangle(base_diameter, base_height).translated(0, base_height / 2)
    chamfer = rectangle(2 * base_chamfer, 2 * base_chamfer).rotated(-45).translated(base_diameter / 2, base_height)
    bottom = bottom - chamfer

    knob = rectangle(base_knob_diameter, base_height + base_knob_height) \
        .translated_y((base_height + base_knob_height) / 2)
    knob_chamfer = rectangle(2 * base_chamfer, 2 * base_chamfer) \
        .rotated(-45) \
        .translated(base_knob_diameter / 2, base_height + base_knob_height)
    knob = knob - knob_chamfer

    base = (bottom + knob).revolved().rotated_x(90)

    return prepared_cube + base 
Example 24
Project: osm2gtfs   Author: grote   File: osm_stops.py    (license) View Source Project 6 votes vote down vote up
def get_center_of_nodes(nodes):
        """Helper function to get center coordinates of a group of nodes

        """
        x = 0
        y = 0
        z = 0

        for node in nodes:
            lat = radians(float(node.lat))
            lon = radians(float(node.lon))

            x += cos(lat) * cos(lon)
            y += cos(lat) * sin(lon)
            z += sin(lat)

        x = float(x / len(nodes))
        y = float(y / len(nodes))
        z = float(z / len(nodes))

        center_lat = degrees(atan2(z, sqrt(x * x + y * y)))
        center_lon = degrees(atan2(y, x))

        return center_lat, center_lon 
Example 25
Project: bpy_lambda   Author: bcongdon   File: mesh_xoffsets.py    (license) View Source Project 6 votes vote down vote up
def prep_rotation_info(ref_pts, r_dat, curr_ms_stor, new_ms_stor):
    #print("curr angle", curr_ms_stor)  # debug
    #print("new angle", new_ms_stor)  # debug

    # workaround for negative angles and angles over 360 degrees
    if new_ms_stor < 0 or new_ms_stor > 360:
        new_ms_stor = new_ms_stor % 360
    r_dat.ang_diff_d = new_ms_stor - curr_ms_stor
    # fix for angles over 180 degrees
    if new_ms_stor > 180:
        r_dat.new_ang_r = radians(180 - (new_ms_stor % 180))
    else:
        r_dat.new_ang_r = radians(new_ms_stor)
    r_dat.ang_diff_r = radians(r_dat.ang_diff_d)
    r_dat.axis_lk = ref_pts.ax_lock


# Takes: ed_type (Editor Type), new_free_co (Vector), ref_pts (ReferencePoints),
# and rDat (RotationData) as args. Uses new_free_co to calculate the rotation
# value and then rotates the selected objects or selected vertices using
# the obtained value. 
Example 26
Project: bpy_lambda   Author: bcongdon   File: mesh_xoffsets.py    (license) View Source Project 6 votes vote down vote up
def updatelock_pts(self, ref_pts):
    global curr_meas_stor
    set_lock_pts(ref_pts)
    if ref_pts.lp_ls == []:
        self.report({'ERROR'}, ref_pts.ax_lock+' axis lock creates identical points')
        ref_pts.lp_ls = ref_pts.rp_ls
        ref_pts.ax_lock = ''
    # update Measurement in curr_meas_stor
    lk_pts = ref_pts.lp_ls
    if ref_pts.cnt < 2:
        curr_meas_stor = 0.0
    elif ref_pts.cnt == 2:
        curr_meas_stor = get_dist(lk_pts[0].co3D, lk_pts[1].co3D)
    elif ref_pts.cnt == 3:
        line_ang_r = get_line_ang_3D(lk_pts[0].co3D, lk_pts[1].co3D, lk_pts[2].co3D)
        curr_meas_stor = degrees(line_ang_r)


# See if key was pressed that would require updating the axis lock info.
# If one was, update the lock points to use new info. 
Example 27
Project: ATX   Author: NetEaseGame   File: android_hooks.py    (license) View Source Project 6 votes vote down vote up
def radang(x, y):
    '''return (radius, angle) of a vector(x, y)'''
    if x == 0:
        if y == 0:
            return 0, 0
        return abs(y), 90+180*(y<0)
    if y == 0:
        return abs(x), 180*(x<0)

    r = math.sqrt(x*x+y*y)
    a = math.degrees(math.atan(y/x))
    if x < 0:
        a += 180
    elif y < 0:
        a += 360
    return r, a 
Example 28
Project: Houston   Author: squaresLab   File: util.py    (license) View Source Project 6 votes vote down vote up
def gps_newpos(lat, lon, bearing, distance):
    """Extrapolate latitude/longitude given a heading and distance
    thanks to http://www.movable-type.co.uk/scripts/latlong.html .
    """
    from math import sin, asin, cos, atan2, radians, degrees

    lat1 = radians(lat)
    lon1 = radians(lon)
    brng = radians(bearing)
    dr = distance / radius_of_earth

    lat2 = asin(sin(lat1) * cos(dr) +
                cos(lat1) * sin(dr) * cos(brng))
    lon2 = lon1 + atan2(sin(brng) * sin(dr) * cos(lat1),
                        cos(dr) - sin(lat1) * sin(lat2))
    return (degrees(lat2), degrees(lon2)) 
Example 29
Project: Houston   Author: squaresLab   File: util.py    (license) View Source Project 6 votes vote down vote up
def current(self, deltat=None):
        """Return current wind speed and direction as a tuple
        speed is in m/s, direction in degrees."""
        if deltat is None:
            tnow = time.time()
            deltat = tnow - self.tlast
            self.tlast = tnow

        # update turbulance random walk
        w_delta = math.sqrt(deltat) * (1.0 - random.gauss(1.0, self.turbulance))
        w_delta -= (self.turbulance_mul - 1.0) * (deltat / self.turbulance_time_constant)
        self.turbulance_mul += w_delta
        speed = self.speed * math.fabs(self.turbulance_mul)
        return (speed, self.direction)

    # Calculate drag. 
Example 30
Project: siren   Author: ozsolarwind   File: grid.py    (license) View Source Project 6 votes vote down vote up
def dust(self, pyd, pxd, y1d, x1d, y2d, x2d):   # debug
        px = radians(pxd)
        py = radians(pyd)
        x1 = radians(x1d)
        y1 = radians(y1d)
        x2 = radians(x2d)
        y2 = radians(y2d)
        p_x = x2 - x1
        p_y = y2 - y1
        something = p_x * p_x + p_y * p_y
        u = ((px - x1) * p_x + (py - y1) * p_y) / float(something)
        if u > 1:
            u = 1
        elif u < 0:
            u = 0
        x = x1 + u * p_x
        y = y1 + u * p_y
        dx = x - px
        dy = y - py
        dist = sqrt(dx * dx + dy * dy)
        return [round(abs(dist) * RADIUS, 2), round(degrees(y), 6), round(degrees(x), 6)] 
Example 31
Project: hand_eye_calibration   Author: ethz-asl   File: dual_quaternion_hand_eye_calibration.py    (license) View Source Project 6 votes vote down vote up
def compute_pose_error(pose_A, pose_B):
  """
  Compute the error norm of position and orientation.
  """
  error_position = np.linalg.norm(pose_A[0:3] - pose_B[0:3], ord=2)

  # Construct quaternions to compare.
  quaternion_A = Quaternion(q=pose_A[3:7])
  quaternion_A.normalize()
  if quaternion_A.w < 0:
    quaternion_A.q = -quaternion_A.q
  quaternion_B = Quaternion(q=pose_B[3:7])
  quaternion_B.normalize()
  if quaternion_B.w < 0:
    quaternion_B.q = -quaternion_B.q

  # Sum up the square of the orientation angle error.
  error_angle_rad = angle_between_quaternions(
      quaternion_A, quaternion_B)
  error_angle_degrees = math.degrees(error_angle_rad)
  if error_angle_degrees > 180.0:
    error_angle_degrees = math.fabs(360.0 - error_angle_degrees)

  return (error_position, error_angle_degrees) 
Example 32
Project: CSB   Author: csb-toolbox   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def to_degrees(self):
        """
        Set angle measurement units to degrees.
        Convert the angles in this TorsionAngles instance to degrees.
        """
        
        if self._units != AngleUnits.Degrees:
    
            phi = TorsionAngles.deg(self._phi)
            psi = TorsionAngles.deg(self._psi)
            omega = TorsionAngles.deg(self._omega)
            
            # if no ValueError is raised by TorsionAngles.check_angle in TorsionAngles.deg:
            # (we assign directly to the instance variables to avoid check_angle being invoked again in setters)
            self._phi, self._psi, self._omega = phi, psi, omega
            self._units = AngleUnits.Degrees 
Example 33
Project: CSB   Author: csb-toolbox   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def deg(angle):    
        """ 
        Convert a torsion angle value, expressed in radians, to degrees.
        Negative angles are not accepted, it is assumed that negative torsion angles have been 
        converted to their ang+2pi counterparts beforehand.  
        
        Return the calculated value in the range of [-180, +180] degrees. 
        """    
        TorsionAngles.check_angle(angle, AngleUnits.Radians)
         
        if angle is not None:                   
            if angle > math.pi:
                angle = -((2. * math.pi) - angle)
            angle = math.degrees(angle)
            
        return angle 
Example 34
Project: Roomba980-Python   Author: NickWaterton   File: roomba.py    (license) View Source Project 6 votes vote down vote up
def draw_text(self, image, display_text, fnt, pos=(0,0),
                  colour=(0,0,255,255), rotate=False):
        #draw text - (WARNING old versions of PIL have huge memory leak here!)
        if display_text is None: return
        self.log.info("MAP: writing text: pos: %s, text: %s"
                      % (pos, display_text))
        if rotate:
            txt = Image.new('RGBA', (fnt.getsize(display_text)),
                            self.transparent)
            text = ImageDraw.Draw(txt)
            # draw text rotated 180 degrees...
            text.text((0,0), display_text, font=fnt, fill=colour)
            image.paste(txt.rotate(180-self.angle, expand=True), pos)
        else:
            text = ImageDraw.Draw(image)
            text.text(pos, display_text, font=fnt, fill=colour) 
Example 35
Project: AutomatorX   Author: xiaoyaojjian   File: android_hooks.py    (license) View Source Project 6 votes vote down vote up
def radang(x, y):
    '''return (radius, angle) of a vector(x, y)'''
    if x == 0:
        if y == 0:
            return 0, 0
        return abs(y), 90+180*(y<0)
    if y == 0:
        return abs(x), 180*(x<0)

    r = math.sqrt(x*x+y*y)
    a = math.degrees(math.atan(y/x))
    if x < 0:
        a += 180
    elif y < 0:
        a += 360
    return r, a 
Example 36
Project: enigma2   Author: Openeight   File: rotor_calc.py    (license) View Source Project 6 votes vote down vote up
def calcAzimuth(SatLon, SiteLat, SiteLon, Height_over_ocean = 0):

	def rev(number):
		return number - math.floor(number / 360.0) * 360

	sinRadSiteLat = math.sin(math.radians(SiteLat))
	cosRadSiteLat = math.cos(math.radians(SiteLat))

	Rstation = r_eq / (math.sqrt(1 - f * (2 - f) * sinRadSiteLat **2))
	Ra = (Rstation + Height_over_ocean) * cosRadSiteLat
	Rz = Rstation * (1 - f) ** 2 * sinRadSiteLat

	alfa_rx = r_sat * math.cos(math.radians(SatLon - SiteLon)) - Ra
	alfa_ry = r_sat * math.sin(math.radians(SatLon - SiteLon))
	alfa_rz = -Rz

	alfa_r_north = -alfa_rx * sinRadSiteLat + alfa_rz * cosRadSiteLat

	if alfa_r_north < 0:
		Azimuth = 180 + math.degrees(math.atan(alfa_ry / alfa_r_north))
	elif alfa_r_north > 0:
		Azimuth = rev(360 + math.degrees(math.atan(alfa_ry / alfa_r_north)))
	else:
		Azimuth = 0
	return Azimuth 
Example 37
Project: enigma2   Author: Openeight   File: rotor_calc.py    (license) View Source Project 6 votes vote down vote up
def calcSatHourangle(SatLon, SiteLat, SiteLon):
	Azimuth = calcAzimuth(SatLon, SiteLat, SiteLon )
	Elevation = calcElevation(SatLon, SiteLat, SiteLon)

	a = - math.cos(math.radians(Elevation)) * math.sin(math.radians(Azimuth))
	b = math.sin(math.radians(Elevation)) * math.cos(math.radians(SiteLat)) - \
		math.cos(math.radians(Elevation)) * math.sin(math.radians(SiteLat)) * \
		math.cos(math.radians(Azimuth))

	# Works for all azimuths (northern & southern hemisphere)
	returnvalue = 180 + math.degrees(math.atan(a / b))

	if Azimuth > 270:
		returnvalue += 180
		if returnvalue > 360:
			returnvalue = 720 - returnvalue

	if Azimuth < 90:
		returnvalue = 180 - returnvalue

	return returnvalue 
Example 38
Project: kharita   Author: vipyoung   File: methods.py    (license) View Source Project 6 votes vote down vote up
def vector_direction_re_north(s, d):
	"""
	Make the source as the reference of the plan. Then compute atan2 of the resulting destination point
	:param s: source point
	:param d: destination point
	:return: angle!
	"""

	# find the new coordinates of the destination point in a plan originated at source.
	new_d_lon = d.lon - s.lon
	new_d_lat = d.lat - s.lat
	angle = -math.degrees(math.atan2(new_d_lat, new_d_lon)) + 90

	# the following is required to move the degrees from -180, 180 to 0, 360
	if angle < 0:
		angle = angle + 360
	return angle 
Example 39
Project: krpc-library   Author: krpc   File: landing.py    (license) View Source Project 6 votes vote down vote up
def coords_down_bearing(lat, lon, bearing, distance, body):
        '''
        Takes a latitude, longitude and bearing in degrees, and a
        distance in meters over a given body.  Returns a tuple
        (latitude, longitude) of the point you've calculated.
        '''
        bearing = math.radians(bearing)
        R = body.equatorial_radius
        lat = math.radians(lat)
        lon = math.radians(lon)
        
        lat2 = math.asin( math.sin(lat)*math.cos(distance/R) +
                     math.cos(lat)*math.sin(distance/R)*math.cos(bearing))

        lon2 = lon + math.atan2(math.sin(bearing)*math.sin(distance/R
                        )*math.cos(lat),math.cos(distance/R)-math.sin(lat
                        )*math.sin(lat2))

        lat2 = math.degrees(lat2)
        lon2 = math.degrees(lon2)
        return (lat2, lon2) 
Example 40
Project: krpc-library   Author: krpc   File: rover.py    (license) View Source Project 6 votes vote down vote up
def heading_for_latlon(target, location):

    lat1 = math.radians(location.lat)
    lat2 = math.radians(target.lat)

    diffLong = math.radians(target.lon - location.lon)

    x = math.sin(diffLong) * math.cos(lat2)
    y = math.cos(lat1) * math.sin(lat2) - (math.sin(lat1)
            * math.cos(lat2) * math.cos(diffLong))

    initial_bearing = math.atan2(x, y)

    initial_bearing = math.degrees(initial_bearing)
    compass_bearing = (initial_bearing + 360) % 360

    return compass_bearing 
Example 41
Project: cvcalib   Author: Algomorph   File: quaternion.py    (license) View Source Project 6 votes vote down vote up
def _set_equatorial(self, equatorial):
        """Set the value of the 3 element equatorial coordinate list [RA,Dec,Roll]
            expects values in degrees
            bounds are not checked
        
            :param equatorial: list or array [ RA, Dec, Roll] in degrees
            
        """
        att = np.array(equatorial)
        ra, dec, roll = att#@UnusedVariable
        self._ra0 = ra
        if (ra > 180):
            self._ra0 = ra - 360
            self._roll0 = roll
        if (roll > 180):
            self._roll0 = roll - 360
        self._equatorial = att 
Example 42
Project: blmath   Author: bodylabs   File: vector_shortcuts.py    (license) View Source Project 6 votes vote down vote up
def angle(v1, v2, look): # FIXME pylint: disable=unused-argument
    '''
    Compute the unsigned angle between two vectors.

    Returns a number between 0 and 180.

    '''
    import math

    # TODO https://bodylabs.atlassian.net/projects/GEN/issues/GEN-1
    # As pylint points out, we are not using `look` here. This method is
    # supposed to be giving the angle between two vectors when viewed along a
    # particular look vector, squashed into a plane. The code here is
    # returning the angle in 3-space, which might be a reasonable function to
    # have, but is not workable for computing the angle between planes as
    # we're doing in bodylabs.measurement.anatomy.Angle.

    dot = normalize(v1).dot(normalize(v2))
    # Dot product sometimes slips past 1 or -1 due to rounding.
    # Can't acos(-1.00001).
    dot = max(min(dot, 1), -1)

    return math.degrees(math.acos(dot)) 
Example 43
Project: crazyswarm   Author: USC-ACTLab   File: visVispy.py    (license) View Source Project 6 votes vote down vote up
def update(self, t, crazyflies):
        if len(self.cfs) == 0:
            verts, faces, normals, nothin = io.read_mesh(os.path.join(os.path.dirname(__file__), "crazyflie2.obj.gz"))
            for i in range(0, len(crazyflies)):
                mesh = scene.visuals.Mesh(vertices=verts, shading='smooth', faces=faces, parent=self.view.scene)
                mesh.transform = transforms.MatrixTransform()
                self.cfs.append(mesh)

        for i in range(0, len(self.cfs)):
            x, y, z = crazyflies[i].position()
            roll, pitch, yaw = crazyflies[i].rpy()
            self.cfs[i].transform.reset()
            self.cfs[i].transform.rotate(90, (1, 0, 0))
            self.cfs[i].transform.rotate(math.degrees(roll), (1, 0, 0))
            self.cfs[i].transform.rotate(math.degrees(pitch), (0, 1, 0))
            self.cfs[i].transform.rotate(math.degrees(yaw), (0, 0, 1))
            self.cfs[i].transform.scale((0.001, 0.001, 0.001))
            self.cfs[i].transform.translate((x, y, z))

        self.canvas.app.process_events() 
Example 44
Project: coa_tools   Author: ndee85   File: export_json.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def get_sprite_rotation(self,sprite_name):
        obj = bpy.data.objects[sprite_name]
        euler_rot = obj.matrix_basis.to_euler()
        degrees = math.degrees(euler_rot[1])
        return -math.radians(degrees)
        
    ### convert windows slashes to linux slashes 
Example 45
Project: coa_tools   Author: ndee85   File: export_dragonbones.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def get_bone_angle(armature,bone,relative=True):
    loc, rot, scale = get_bone_matrix(armature,bone,relative).decompose()
    compat_euler = Euler((0.0,0.0,math.pi),"XYZ")
    angle = -rot.to_euler().z  # negate angle to fit dragonbones angle
        
    return round(math.degrees(angle),2) 
Example 46
Project: tree-gen   Author: friggog   File: chturtle.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def declination(self):
        """Calculate declination of vector in degrees"""
        return math.degrees(math.atan2(math.sqrt(self.x ** 2 + self.y ** 2), self.z)) 
Example 47
Project: ImageFudge   Author: Team-Zero-G   File: utils.py    (MIT License) View Source Project 5 votes vote down vote up
def get_angle(origin, endpoint):
        """ Returns the angle created by the line from origin to endpoint """
        dx = endpoint.x - origin.x
        dy = endpoint.y - origin.y
        return math.degrees(math.atan2(dy, dx)) 
Example 48
Project: zellij   Author: nedbat   File: euclid.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def angle(self):
        """The angle in degrees this line makes to the horizontal."""
        (x1, y1), (x2, y2) = self
        return math.degrees(math.atan2(y2 - y1, x2 - x1)) 
Example 49
Project: dabdabrevolution   Author: harryparkdotio   File: armRadio.py    (MIT License) View Source Project 5 votes vote down vote up
def getPitch():
    x = accelerometer.get_x() / 1024
    y = accelerometer.get_y() / 1024
    z = accelerometer.get_z() / 1024
    
    return math.degrees(math.atan(y/((math.sqrt(x**2 + z**2) if math.sqrt(x**2 + z**2) != 0 else 0.1)))) 
Example 50
Project: pycraft   Author: traverseda   File: character.py    (MIT License) View Source Project 5 votes vote down vote up
def __init__(self, config):
        # general world configuration
        self.config = config
        # To derive the formula for calculating jump speed, first solve
        #    v_t = v_0 + a * t
        # for the time at which you achieve maximum height, where a is the acceleration
        # due to gravity and v_t = 0. This gives:
        #    t = - v_0 / a
        # Use t and the desired MAX_JUMP_HEIGHT to solve for v_0 (jump speed) in
        #    s = s_0 + v_0 * t + (a * t^2) / 2
        self.jump_speed = math.sqrt(2 * self.config['gravity'] * self.config['max_jump_height'])
        # When flying gravity has no effect and speed is increased.
        self.flying = False
        # Strafing is moving lateral to the direction you are facing,
        # e.g. moving to the left or right while continuing to face forward.
        #
        # First element is -1 when moving forward, 1 when moving back, and 0
        # otherwise. The second element is -1 when moving left, 1 when moving
        # right, and 0 otherwise.
        self.strafe = [0, 0]
        # This is strafing in the absolute up/down position, not
        # relative to where the player is facing. 1 when moving up, -1 when moving down
        self.strafe_z = 0
        # Current (x, y, z) position in the world, specified with floats. Note
        # that, perhaps unlike in math class, the y-axis is the vertical axis.
        self.position = (0, 5, 0)
        # First element is rotation of the player in the x-z plane (ground
        # plane) measured from the z-axis down. The second is the rotation
        # angle from the ground plane up. Rotation is in degrees.
        #
        # The vertical plane rotation ranges from -90 (looking straight down) to
        # 90 (looking straight up). The horizontal rotation range is unbounded.
        self.rotation = (0, 0)
        # Velocity in the y (upward) direction.
        self.dy = 0