Python math.degrees() Examples

The following are 30 code examples of math.degrees(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module math , or try the search function .
Example #1
Source File: mapping.py    From dcs with GNU Lesser General Public License v3.0 7 votes vote down vote up
def heading_between_points(x1, y1, x2, y2):
    """Returns the angle between 2 points in degrees.

    :param x1: x coordinate of point 1
    :param y1: y coordinate of point 1
    :param x2: x coordinate of point 2
    :param y2: y coordinate of point 2
    :return: angle in degrees
    """
    def angle_trunc(a):
        while a < 0.0:
            a += math.pi * 2
        return a
    deltax = x2 - x1
    deltay = y2 - y1
    return math.degrees(angle_trunc(math.atan2(deltay, deltax))) 
Example #2
Source File: locations.py    From orbit-predictor with MIT License 6 votes vote down vote up
def __init__(self, name, latitude_deg, longitude_deg, elevation_m):
        """Location.

        Parameters
        ----------
        latitude_deg : float
            Latitude in degrees.
        longitude_deg : float
            Longitude in degrees.
        elevation_m : float
            Elevation in meters.

        """
        self.name = name
        self.latitude_deg = latitude_deg
        self.longitude_deg = longitude_deg
        self.elevation_m = elevation_m
        self.position_ecef = coordinate_systems.geodetic_to_ecef(
            radians(latitude_deg),
            radians(longitude_deg),
            elevation_m / 1000.)
        self.position_llh = latitude_deg, longitude_deg, elevation_m 
Example #3
Source File: shapes.py    From symbolator with MIT License 6 votes vote down vote up
def rotate_bbox(box, a):
  '''Rotate a bounding box 4-tuple by an angle in degrees'''
  corners = ( (box[0], box[1]), (box[0], box[3]), (box[2], box[3]), (box[2], box[1]) )
  a = -math.radians(a)
  sa = math.sin(a)
  ca = math.cos(a)
  
  rot = []
  for p in corners:
    rx = p[0]*ca + p[1]*sa
    ry = -p[0]*sa + p[1]*ca
    rot.append((rx,ry))
  
  # Find the extrema of the rotated points
  rot = list(zip(*rot))
  rx0 = min(rot[0])
  rx1 = max(rot[0])
  ry0 = min(rot[1])
  ry1 = max(rot[1])

  #print('## RBB:', box, rot)
    
  return (rx0, ry0, rx1, ry1) 
Example #4
Source File: geomath.py    From AboveTustin with MIT License 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 #5
Source File: linalg.py    From NURBS-Python with MIT License 6 votes vote down vote up
def vector_angle_between(vector1, vector2, **kwargs):
    """ Computes the angle between the two input vectors.

    If the keyword argument ``degrees`` is set to *True*, then the angle will be in degrees. Otherwise, it will be
    in radians. By default, ``degrees`` is set to *True*.

    :param vector1: vector
    :type vector1: list, tuple
    :param vector2: vector
    :type vector2: list, tuple
    :return: angle between the vectors
    :rtype: float
    """
    degrees = kwargs.get('degrees', True)
    magn1 = vector_magnitude(vector1)
    magn2 = vector_magnitude(vector2)
    acos_val = vector_dot(vector1, vector2) / (magn1 * magn2)
    angle_radians = math.acos(acos_val)
    if degrees:
        return math.degrees(angle_radians)
    else:
        return angle_radians 
Example #6
Source File: epidemic.py    From indras_net with GNU General Public License v3.0 6 votes vote down vote up
def opposing_angle(pos1, pos2):
    '''
    Returns the angle of the other_agent relative to the agent
    '''
    x_dif = pos2[0] - pos1[0]
    y_dif = pos2[1] - pos1[1]
    if (x_dif != 0 and y_dif != 0):
        if (x_dif > 0):
            new_angle = 180 + degrees(atan(y_dif / x_dif))
        else:
            new_angle = degrees(atan(y_dif / x_dif))
    elif (y_dif != 0):
        if(y_dif > 0):
            new_angle = 270
        else:
            new_angle = 90
    else:
        if(x_dif > 0):
            new_angle = 180
        else:
            new_angle = 0
    return new_angle 
Example #7
Source File: __init__.py    From Arnold-For-Blender with GNU General Public License v3.0 6 votes vote down vote up
def _view_update_camera(aspect, v3d, rv3d, camera):
    zoom = rv3d.view_camera_zoom
    z = ((_SQRT2 + zoom / 50) ** 2) / 4

    cdata = v3d.camera.data
    fit = cdata.sensor_fit
    if fit == 'VERTICAL':
        sensor = cdata.sensor_height
        _sensor = (16 * sensor / 9) / z  # sensor / (18 / 32)
        z *= 9 / 16  # 18 / 32
    else:
        sensor = cdata.sensor_width
        _sensor = sensor / z
    lens = cdata.lens
    camera['fov'] = ('FLOAT', math.degrees(2 * math.atan(_sensor / (2 * lens))))

    offset_x, offset_y = rv3d.view_camera_offset
    shift_x = cdata.shift_x
    shift_y = cdata.shift_y
    shx = 2 * z * (2 * offset_x + shift_x)
    shy = 2 * z * (2 * offset_y + shift_y * aspect)
    camera['screen_window_min'] = ('VECTOR2', (-1, -1))
    camera['screen_window_max'] = ('VECTOR2', (1, 1))

    return (zoom, fit, sensor, lens, offset_x, offset_y, shift_x, shift_y) 
Example #8
Source File: mapping.py    From dcs with GNU Lesser General Public License v3.0 6 votes vote down vote up
def point_from_heading(_x, _y, heading, distance):
    """Calculates a point from a given point, heading and distance.

    :param _x: source point x
    :param _y: source point y
    :param heading: heading in degrees from source point
    :param distance: distance from source point
    :return: returns a tuple (x, y) of the calculated point
    """
    while heading < 0:
        heading += 360
    heading %= 360
    rad_heading = math.radians(heading)
    x = _x + math.cos(rad_heading) * distance
    y = _y + math.sin(rad_heading) * distance

    return x, y 
Example #9
Source File: rigeditor.py    From renpy-shader with MIT License 6 votes vote down vote up
def visualizeBoneProperties(self, bone, mouse):
        color = (0, 0, 0)
        x = 10
        y = 10

        name = bone.name
        if bone.mesh:
            name += " (%i polygons, %i vertices)" % (len(bone.mesh.indices) // 3, len(bone.mesh.vertices) // 2)
        y += self.drawText(name, HEADER_COLOR, (x, y))[1]

        y += self.drawText("Translation: (%.1f, %.1f)" % (bone.translation.x,  bone.translation.y), color, (x, y))[1]

        degrees = tuple([math.degrees(d) for d in (bone.rotation.x,  bone.rotation.y,  bone.rotation.z)])
        y += self.drawText("Rotation:      (%.1f, %.1f, %.1f)" % degrees, color, (x, y))[1]

        y += self.drawText("Scale:          (%.1f, %.1f, %.1f)" % (bone.scale.x,  bone.scale.y,  bone.scale.z), color, (x, y))[1]

        self.drawText("Z-order:       %i" % bone.zOrder, color, (x, y)) 
Example #10
Source File: spore_sampler.py    From spore with MIT License 6 votes vote down vote up
def slope_filter(self, min_slope, max_slope, fuzz):

        world = om.MVector(0, 1, 0)

        invalid_ids = []
        for i, (_, normal, _, _, _) in enumerate(self.point_data):
            normal = om.MVector(normal[0], normal[1], normal[2])
            angle = math.degrees(normal.angle(world)) + 45 * random.uniform(-fuzz, fuzz)

            if angle < min_slope or angle > max_slope:
                invalid_ids.append(i)

        invalid_ids = sorted(invalid_ids, reverse=True)
        [self.point_data.remove(index) for index in invalid_ids]


        pass 
Example #11
Source File: spore_sampler.py    From spore with MIT License 6 votes vote down vote up
def get_rotation(self, direction, weight, min_rot, max_rot):
        """ get rotation from a matrix pointing towards the given direction
        slerped by the given weight into the world up vector and added a random
        rotation between min and max rotation """

        r_x = math.radians(random.uniform(min_rot[0], max_rot[0]))
        r_y = math.radians(random.uniform(min_rot[1], max_rot[1]))
        r_z = math.radians(random.uniform(min_rot[2], max_rot[2]))
        util = om.MScriptUtil()
        util.createFromDouble(r_x, r_y, r_z)
        rotation_ptr = util.asDoublePtr()

        matrix = om.MTransformationMatrix()
        matrix.setRotation(rotation_ptr, om.MTransformationMatrix.kXYZ)
        world_up = om.MVector(0, 1, 0)
        rotation = om.MQuaternion(world_up, direction, weight)
        matrix = matrix.asMatrix() * rotation.asMatrix()
        rotation = om.MTransformationMatrix(matrix).rotation().asEulerRotation()

        return om.MVector(math.degrees(rotation.x),
                          math.degrees(rotation.y),
                          math.degrees(rotation.z)) 
Example #12
Source File: weather_sim.py    From scenario_runner with MIT License 6 votes vote down vote up
def update(self, delta_time=0):
        """
        If the weather animation is true, the new sun position is calculated w.r.t delta_time

        Nothing happens if animation or datetime are None.

        Args:
            delta_time (float): Time passed since self.datetime [seconds].
        """
        if not self.animation or not self.datetime:
            return

        self.datetime = self.datetime + datetime.timedelta(seconds=delta_time)
        self._observer_location.date = self.datetime

        self._sun.compute(self._observer_location)
        self.carla_weather.sun_altitude_angle = math.degrees(self._sun.alt)
        self.carla_weather.sun_azimuth_angle = math.degrees(self._sun.az) 
Example #13
Source File: demo_main.py    From centerpose with MIT License 6 votes vote down vote up
def add_coco_hp(image, points, color): 
    for j in range(17):
        cv2.circle(image,
                 (points[j, 0], points[j, 1]), 2, (int(color[0]), int(color[1]), int(color[2])), -1)
                 
    stickwidth = 2
    cur_canvas = image.copy()             
    for j, e in enumerate(_kp_connections):
        if points[e].min() > 0:
            X = [points[e[0], 1], points[e[1], 1]]
            Y = [points[e[0], 0], points[e[1], 0]]
            mX = np.mean(X)
            mY = np.mean(Y)
            length = ((X[0] - X[1]) ** 2 + (Y[0] - Y[1]) ** 2) ** 0.5
            angle = math.degrees(math.atan2(X[0] - X[1], Y[0] - Y[1]))
            polygon = cv2.ellipse2Poly((int(mY),int(mX)), (int(length/2), stickwidth), int(angle), 0, 360, 1)
            cv2.fillConvexPoly(cur_canvas, polygon, (int(color[0]), int(color[1]), int(color[2])))
            image = cv2.addWeighted(image, 0.5, cur_canvas, 0.5, 0)

    return image 
Example #14
Source File: debugger.py    From centerpose with MIT License 6 votes vote down vote up
def add_coco_hp(self, points, points_prob, img_id='default'): 
        points = np.array(points, dtype=np.int32).reshape(self.num_joints, 2)
        points_prob = np.array(points_prob, dtype=np.float32).reshape(self.num_joints)

        for j in range(self.num_joints):
            if points_prob[j]>0.:
                cv2.circle(self.imgs[img_id],
                          (points[j, 0], points[j, 1]), 2, (255,255,255), -1)
                         
        stickwidth = 2
        cur_canvas = self.imgs[img_id].copy()             
        for j, e in enumerate(self.edges):
            if points_prob[e[0]] > 0. and points_prob[e[1]] > 0.:
                X = [points[e[0], 1], points[e[1], 1]]
                Y = [points[e[0], 0], points[e[1], 0]]
                mX = np.mean(X)
                mY = np.mean(Y)
                length = ((X[0] - X[1]) ** 2 + (Y[0] - Y[1]) ** 2) ** 0.5
                angle = math.degrees(math.atan2(X[0] - X[1], Y[0] - Y[1]))
                polygon = cv2.ellipse2Poly((int(mY),int(mX)), (int(length/2), stickwidth), int(angle), 0, 360, 1)
                cv2.fillConvexPoly(cur_canvas, polygon, (255, 255, 255))
                self.imgs[img_id] = cv2.addWeighted(self.imgs[img_id], 0.8, cur_canvas, 0.2, 0) 
Example #15
Source File: macros.py    From pyth with MIT License 6 votes vote down vote up
def trig(a, b=' '):
    if is_num(a) and isinstance(b, int):

        funcs = [math.sin, math.cos, math.tan,
                 math.asin, math.acos, math.atan,
                 math.degrees, math.radians,
                 math.sinh, math.cosh, math.tanh,
                 math.asinh, math.acosh, math.atanh]

        return funcs[b](a)

    if is_lst(a):
        width = max(len(row) for row in a)
        padded_matrix = [list(row) + (width - len(row)) * [b] for row in a]
        transpose = list(zip(*padded_matrix))
        if all(isinstance(row, str) for row in a) and isinstance(b, str):
            normalizer = ''.join
        else:
            normalizer = list
        norm_trans = [normalizer(padded_row) for padded_row in transpose]
        return norm_trans
    return unknown_types(trig, ".t", a, b) 
Example #16
Source File: module.py    From PynPoint with GNU General Public License v3.0 6 votes vote down vote up
def angle_average(angles: np.ndarray) -> float:
    """
    Function to calculate the average value of a list of angles.

    Parameters
    ----------
    angles : numpy.ndarray
        Parallactic angles (deg).

    Returns
    -------
    float
        Average angle (deg).
    """

    cmath_rect = sum(cmath.rect(1, math.radians(ang)) for ang in angles)
    cmath_phase = cmath.phase(cmath_rect/len(angles))

    return math.degrees(cmath_phase) 
Example #17
Source File: camera-calibration-pvr.py    From camera-calibration-pvr with GNU General Public License v2.0 6 votes vote down vote up
def reconstruct_rectangle(pa, pb, pc, pd, scale, focal):
    # Calculate the coordinates of the rectangle in 3d
    coords = get_lambda_d(pa, pb, pc, pd, scale, focal)
    # Calculate the transformation of the rectangle
    trafo = get_transformation(coords[0], coords[1], coords[2], coords[3])
    # Reconstruct the rotation angles of the transformation
    angles = get_rot_angles(trafo[0], trafo[1], trafo[2])
    xyz_matrix = mathutils.Euler((angles[0], angles[1], angles[2]), "XYZ")
    # Reconstruct the camera position and the corners of the rectangle in 3d such that it lies on the xy-plane
    tr = trafo[-1]
    cam_pos = apply_transformation([mathutils.Vector((0.0, 0.0, 0.0))], tr, xyz_matrix)[0]
    corners = apply_transformation(coords, tr, xyz_matrix)
    # Printout for debugging
    print("Focal length:", focal)
    print("Camera rotation:", degrees(angles[0]), degrees(angles[1]), degrees(angles[2]))
    print("Camera position:", cam_pos)
    length = (coords[0] - coords[1]).length
    width = (coords[0] - coords[3]).length
    size = max(length, width)
    print("Rectangle length:", length)
    print("Rectangle width:", width)
    print("Rectangle corners:", corners)
    return (cam_pos, xyz_matrix, corners, size) 
Example #18
Source File: wwPath.py    From WonderPy with MIT License 5 votes vote down vote up
def _calc_theta_index_deg(self, point_index):
        nrm = self._calc_direction_index(point_index)
        x, y = wwMath.coords_api_to_json_pos(nrm[0], nrm[1])
        nrm = (x, y)
        return math.degrees(wwMath.direction_to_angle_rads(nrm))

    # calculate a unit-length direction vector for a given point in self.points.
    # this attempts to be the tangent to the path at the vertex. 
Example #19
Source File: wwSensorGyroscope.py    From WonderPy with MIT License 5 votes vote down vote up
def parse(self, single_component_dictionary):
        if not self.check_fields_exist(single_component_dictionary, _expected_json_fields):
            return

        x = single_component_dictionary[_rcv.WW_SENSOR_VALUE_AXIS_ROLL ]
        y = single_component_dictionary[_rcv.WW_SENSOR_VALUE_AXIS_PITCH]
        z = single_component_dictionary[_rcv.WW_SENSOR_VALUE_AXIS_YAW  ]

        x, y = wwMath.coords_json_to_api_pos(x, y)

        self._x = math.degrees(x)
        self._y = math.degrees(y)
        self._z = math.degrees(z)

        self._valid   = True 
Example #20
Source File: test_math.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def testDegrees(self):
        self.assertRaises(TypeError, math.degrees)
        self.ftest('degrees(pi)', math.degrees(math.pi), 180.0)
        self.ftest('degrees(pi/2)', math.degrees(math.pi/2), 90.0)
        self.ftest('degrees(-pi/4)', math.degrees(-math.pi/4), -45.0) 
Example #21
Source File: sphere.py    From sphere with MIT License 5 votes vote down vote up
def degrees(self):
        return math.degrees(self.__radians) 
Example #22
Source File: wwCommandBody.py    From WonderPy with MIT License 5 votes vote down vote up
def compose_pose(self, x_cm, y_cm, degrees, time, mode, ease, direction, wrap_theta):
        x_cm, y_cm = wwMath.coords_api_to_json_pos(x_cm, y_cm)
        degrees    = wwMath.coords_api_to_json_pan(degrees)

        args = {}
        args[_rcv.WW_COMMAND_VALUE_AXIS_X         ] = x_cm
        args[_rcv.WW_COMMAND_VALUE_AXIS_Y         ] = y_cm
        args[_rcv.WW_COMMAND_VALUE_ANGLE_DEGREE   ] = degrees
        args[_rcv.WW_COMMAND_VALUE_TIME           ] = time
        args[_rcv.WW_COMMAND_VALUE_POSE_EASE      ] = ease
        args[_rcv.WW_COMMAND_VALUE_POSE_MODE      ] = mode
        args[_rcv.WW_COMMAND_VALUE_POSE_WRAP_THETA] = wrap_theta
        args[_rcv.WW_COMMAND_VALUE_POSE_DIRECTION ] = direction
        return {_rc.WW_COMMAND_BODY_POSE : args} 
Example #23
Source File: wwPath.py    From WonderPy with MIT License 5 votes vote down vote up
def __init__(self):
            self.x_cm     = 0
            self.y_cm     = 0
            self.degrees  = 0
            self.duration = 0
            self.apt      = 0 
Example #24
Source File: wwSensorAccelerometer.py    From WonderPy with MIT License 5 votes vote down vote up
def degrees_z_yz(self):
        """
        degrees away from z axis in the yz plane. note undefined if yz is horizontal
        """
        return math.atan2(self.y, self.z) * math.degrees(1) 
Example #25
Source File: wwSensorAccelerometer.py    From WonderPy with MIT License 5 votes vote down vote up
def degrees_y_yz(self):
        """
        degrees away from y axis in the yz plane. note undefined if yz is horizontal
        """
        return math.atan2(self.z, self.y) * math.degrees(1) 
Example #26
Source File: wwSensorAccelerometer.py    From WonderPy with MIT License 5 votes vote down vote up
def degrees_z_xz(self):
        """
        degrees away from z axis in the xz plane. note undefined if xz is horizontal
        """
        return math.atan2(self.x, self.z) * math.degrees(1) 
Example #27
Source File: wwSensorAccelerometer.py    From WonderPy with MIT License 5 votes vote down vote up
def degrees_y_xy(self):
        """
        degrees away from y axis in the xy plane. note undefined if xy is horizontal
        """
        return math.atan2(self.x, self.y) * math.degrees(1) 
Example #28
Source File: wwSensorAccelerometer.py    From WonderPy with MIT License 5 votes vote down vote up
def degrees_x_xy(self):
        """
        degrees away from y axis in the xy plane. note undefined if xy is horizontal
        """
        return math.atan2(self.y, self.x) * math.degrees(1) 
Example #29
Source File: wwCommandBody.py    From WonderPy with MIT License 5 votes vote down vote up
def do_pose(self, x_cm, y_cm, degrees, time, mode=WWRobotConstants.WWPoseMode.WW_POSE_MODE_RELATIVE_MEASURED, ease=True,
                direction=WWRobotConstants.WWPoseDirection.WW_POSE_DIRECTION_INFERRED,
                wrap_theta=True):
        self.stage_pose(x_cm, y_cm, degrees, time, mode, ease, direction, wrap_theta)
        self._robot.sensors.pose.block_until_idle(time + 10.0) 
Example #30
Source File: wwPath.py    From WonderPy with MIT License 5 votes vote down vote up
def do_piecewise(self, robot):
        poses = self.generate_poses()

        robot.block_until_sensors()

        for pose in poses:
            print("pose: %s" % (str(pose)))
            robot.cmds.body.do_pose(pose.x_cm, pose.y_cm, pose.degrees, pose.duration,
                                    WWRobotConstants.WWPoseMode.WW_POSE_MODE_GLOBAL)