Python math.radians() Examples

The following are 30 code examples of math.radians(). 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 Project: AboveTustin   Author: kevinabrandon   File: geomath.py    License: 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 #2
Source Project: pepper-robot-programming   Author: maverickjoy   File: asthama_search.py    License: MIT License 6 votes vote down vote up
def _startImageCapturingAtGraphNode(self):
        amntY = 0.3
        xdir = [-0.5, 0, 0.5]
        cameraId = 0

        for idx,amntX in enumerate(xdir):
            self._moveHead(amntX, amntY)
            time.sleep(0.1)
            self._checkIfAsthamaInEnvironment(cameraId)
            if self.pumpFound :
                # Setting rotation angle of body towards head
                theta = 0
                if idx == 0: # LEFT
                    theta = math.radians(-45)
                if idx == 2: # RIGHT
                    theta = math.radians(45)
                self.pumpAngleRotation = theta

                return "KILLING GRAPH SEARCH : PUMP FOUND"

        self._moveHead(0, 0) # Bringing to initial view

        return 
Example #3
Source Project: L.E.S.M.A   Author: NatanaelAntonioli   File: L.E.S.M.A. - Fabrica de Noobs Speedtest.py    License: Apache License 2.0 6 votes vote down vote up
def distance(origin, destination):
	"""Determine distance between 2 sets of [lat,lon] in km"""

	lat1, lon1 = origin
	lat2, lon2 = destination
	radius = 6371  # km

	dlat = math.radians(lat2 - lat1)
	dlon = math.radians(lon2 - lon1)
	a = (math.sin(dlat / 2) * math.sin(dlat / 2) +
		 math.cos(math.radians(lat1)) *
		 math.cos(math.radians(lat2)) * math.sin(dlon / 2) *
		 math.sin(dlon / 2))
	c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
	d = radius * c

	return d 
Example #4
Source Project: symbolator   Author: kevinpt   File: shapes.py    License: 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 #5
Source Project: symbolator   Author: kevinpt   File: cairo_backend.py    License: MIT License 6 votes vote down vote up
def draw_marker(self, name, mp, tp, weight, c):
    if name in self.markers:
      m_shape, ref, orient, units = self.markers[name]

      c.save()
      c.translate(*mp)
      if orient == 'auto':
        angle = math.atan2(tp[1]-mp[1], tp[0]-mp[0])
        c.rotate(angle)
      elif isinstance(orient, int):
        angle = math.radians(orient)
        c.rotate(angle)

      if units == 'stroke':
        c.scale(weight, weight)
        
      c.translate(-ref[0], -ref[1])
      
      self.draw_shape(m_shape)
      c.restore() 
Example #6
Source Project: QPong   Author: HuangJunye   File: ball.py    License: Apache License 2.0 6 votes vote down vote up
def update(self):
        radians = math.radians(self.direction)

        self.x += self.speed * math.sin(radians)
        self.y -= self.speed * math.cos(radians)

        # Update ball position
        self.rect.x = self.x
        self.rect.y = self.y

        if self.y <= self.top_edge:
            self.direction = (180-self.direction) % 360
            self.sound.edge_sound.play()
        if self.y > self.bottom_edge - 1*self.height:
            self.direction = (180-self.direction) % 360
            self.sound.edge_sound.play() 
Example #7
Source Project: Localization   Author: kamalshadi   File: geometry.py    License: MIT License 6 votes vote down vote up
def gcd(self, lon1, lat1, lon2, lat2):
        """
        Calculate the great circle distance between two points
        on the earth (specified in decimal degrees)
        """
        # convert decimal degrees to radians
        lon1, lat1, lon2, lat2 = map(math.radians, [lon1, lat1, lon2, lat2])

        # 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))

        dis = E.R * c
        return dis 
Example #8
Source Project: dronekit-python   Author: dronekit   File: set_attitude_target.py    License: Apache License 2.0 6 votes vote down vote up
def to_quaternion(roll = 0.0, pitch = 0.0, yaw = 0.0):
    """
    Convert degrees to quaternions
    """
    t0 = math.cos(math.radians(yaw * 0.5))
    t1 = math.sin(math.radians(yaw * 0.5))
    t2 = math.cos(math.radians(roll * 0.5))
    t3 = math.sin(math.radians(roll * 0.5))
    t4 = math.cos(math.radians(pitch * 0.5))
    t5 = math.sin(math.radians(pitch * 0.5))

    w = t0 * t2 * t4 + t1 * t3 * t5
    x = t0 * t3 * t4 - t1 * t2 * t5
    y = t0 * t2 * t5 + t1 * t3 * t4
    z = t1 * t2 * t4 - t0 * t3 * t5

    return [w, x, y, z]

# Take off 2.5m in GUIDED_NOGPS mode. 
Example #9
Source Project: sphere   Author: qedus   File: sphere.py    License: MIT License 6 votes vote down vote up
def contains(self, *args):
        if isinstance(args[0], Point):
            point = args[0]
            return self.contains(LatLon.from_point(point))
        elif isinstance(args[0], LatLon):
            ll = args[0]
            assert ll.is_valid()
            return self.lat().contains(ll.lat().radians) \
                    and self.lon().contains(ll.lon().radians)
        elif isinstance(args[0], self.__class__):
            other = args[0]
            return self.lat().contains(other.lat()) \
                    and self.lon().contains(other.lon())
        elif isinstance(args[0], Cell):
            cell = args[0]
            return self.contains(cell.get_rect_bound())
        else:
            raise NotImplementedError() 
Example #10
Source Project: 3D-R2N2   Author: chrischoy   File: blender_renderer.py    License: MIT License 6 votes vote down vote up
def _set_lighting(self):
        # Create new lamp datablock
        light_data = bpy.data.lamps.new(name="New Lamp", type='HEMI')

        # Create new object with our lamp datablock
        light_2 = bpy.data.objects.new(name="New Lamp", object_data=light_data)
        bpy.context.scene.objects.link(light_2)

        # put the light behind the camera. Reduce specular lighting
        self.light.location       = (0, -2, 2)
        self.light.rotation_mode  = 'ZXY'
        self.light.rotation_euler = (radians(45), 0, radians(90))
        self.light.data.energy = 0.7

        light_2.location       = (0, 2, 2)
        light_2.rotation_mode  = 'ZXY'
        light_2.rotation_euler = (-radians(45), 0, radians(90))
        light_2.data.energy = 0.7 
Example #11
Source Project: 3D-R2N2   Author: chrischoy   File: blender_renderer.py    License: MIT License 6 votes vote down vote up
def _set_lighting(self):
        self.light.location       = (0, 3, 3)
        self.light.rotation_mode  = 'ZXY'
        self.light.rotation_euler = (-radians(45), 0, radians(90))
        self.light.data.energy = 0.7

        # Create new lamp datablock
        light_data = bpy.data.lamps.new(name="New Lamp", type='HEMI')

        # Create new object with our lamp datablock
        light_2 = bpy.data.objects.new(name="New Lamp", object_data=light_data)
        bpy.context.scene.objects.link(light_2)

        light_2.location       = (4, 1, 6)
        light_2.rotation_mode  = 'XYZ'
        light_2.rotation_euler = (radians(37), radians(3), radians(106))
        light_2.data.energy = 0.7 
Example #12
Source Project: honeybee   Author: ladybug-tools   File: room.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, name=None, origin=(0, 0, 0), width=3.0, depth=6.0, height=3.2,
                 rotation_angle=0):
        """Init room."""
        self._width = float(width) or 3.0
        self._depth = float(depth) or 6.0
        self._height = float(height) or 3.2
        self._rotation_angle = float(rotation_angle) or 0.0

        self._z_axis = Vector3(0, 0, 1)
        self._x_axis = Vector3(1, 0, 0).rotate_around(
            self._z_axis, math.radians(rotation_angle))
        self._y_axis = Vector3(0, 1, 0).rotate_around(
            self._z_axis, math.radians(rotation_angle))

        name = name or 'room'
        origin = Point3(*tuple(origin)) if origin else Point3(0, 0, 0)
        # setting up origin will initiate recalculation of room
        HBZone.__init__(self, name, origin) 
Example #13
Source Project: opencv_transforms   Author: jbohnslav   File: functional.py    License: MIT License 6 votes vote down vote up
def _get_affine_matrix(center, angle, translate, scale, shear):
    # Helper method to compute matrix for affine transformation
    # We need compute affine transformation matrix: M = T * C * RSS * C^-1
    # where T is translation matrix: [1, 0, tx | 0, 1, ty | 0, 0, 1]
    #       C is translation matrix to keep center: [1, 0, cx | 0, 1, cy | 0, 0, 1]
    #       RSS is rotation with scale and shear matrix
    #       RSS(a, scale, shear) = [ cos(a)*scale    -sin(a + shear)*scale     0]
    #                              [ sin(a)*scale    cos(a + shear)*scale     0]
    #                              [     0                  0          1]
    
    angle = math.radians(angle)
    shear = math.radians(shear)
    # scale = 1.0 / scale
    
    T = np.array([[1, 0, translate[0]], [0, 1, translate[1]], [0,0,1]])
    C = np.array([[1, 0, center[0]], [0, 1, center[1]], [0,0,1]])
    RSS = np.array([[math.cos(angle)*scale, -math.sin(angle+shear)*scale, 0],
                   [math.sin(angle)*scale, math.cos(angle+shear)*scale, 0],
                   [0,0,1]])
    matrix = T @ C @ RSS @ np.linalg.inv(C)
    
    return matrix[:2,:] 
Example #14
Source Project: BiblioPixel   Author: ManiacalLabs   File: util.py    License: MIT License 6 votes vote down vote up
def pointOnCircle(cx, cy, radius, angle):
    """
    Calculates the coordinates of a point on a circle given the center point,
    radius, and angle.
    """
    angle = math.radians(angle) - (math.pi / 2)
    x = cx + radius * math.cos(angle)
    if x < cx:
        x = math.ceil(x)
    else:
        x = math.floor(x)

    y = cy + radius * math.sin(angle)

    if y < cy:
        y = math.ceil(y)
    else:
        y = math.floor(y)

    return (int(x), int(y)) 
Example #15
Source Project: deep-smoke-machine   Author: CMU-CREATE-Lab   File: opencv_functional.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _get_affine_matrix(center, angle, translate, scale, shear):
    # Helper method to compute matrix for affine transformation
    # We need compute affine transformation matrix: M = T * C * RSS * C^-1
    # where T is translation matrix: [1, 0, tx | 0, 1, ty | 0, 0, 1]
    #       C is translation matrix to keep center: [1, 0, cx | 0, 1, cy | 0, 0, 1]
    #       RSS is rotation with scale and shear matrix
    #       RSS(a, scale, shear) = [ cos(a)*scale    -sin(a + shear)*scale     0]
    #                              [ sin(a)*scale    cos(a + shear)*scale     0]
    #                              [     0                  0          1]

    angle = math.radians(angle)
    shear = math.radians(shear)
    # scale = 1.0 / scale

    T = np.array([[1, 0, translate[0]], [0, 1, translate[1]], [0,0,1]])
    C = np.array([[1, 0, center[0]], [0, 1, center[1]], [0,0,1]])
    RSS = np.array([[math.cos(angle)*scale, -math.sin(angle+shear)*scale, 0],
                   [math.sin(angle)*scale, math.cos(angle+shear)*scale, 0],
                   [0,0,1]])
    matrix = T @ C @ RSS @ np.linalg.inv(C)

    return matrix[:2,:] 
Example #16
Source Project: usv_sim_lsa   Author: disaster-robotics-proalertas   File: sail_polar_diagram.py    License: Apache License 2.0 6 votes vote down vote up
def set_sailboat_heading(pub_state):
    global current_state
    global current_sail
    state_aux = ModelState()
    quaternion = (current_state.pose.pose.orientation.x, current_state.pose.pose.orientation.y, current_state.pose.pose.orientation.z, current_state.pose.pose.orientation.w)

    euler = tf.transformations.euler_from_quaternion(quaternion)

    quaternion = tf.transformations.quaternion_from_euler(euler[0], euler[1], math.radians(current_heading))
    state_aux.pose.orientation.x = quaternion[0]
    state_aux.pose.orientation.y = quaternion[1]
    state_aux.pose.orientation.z = quaternion[2]
    state_aux.pose.orientation.w = quaternion[3]
    state_aux.model_name = 'sailboat'
    #state_aux.pose.position.x = current_state.pose.pose.position.x
    #state_aux.pose.position.y = current_state.pose.pose.position.y
    #state_aux.pose.position.z = current_state.pose.pose.position.z
    #print(current_state)

    state_aux.pose.position.x = 240 
    state_aux.pose.position.y = 95
    state_aux.pose.position.z = 1
    pub_state.publish(state_aux) 
Example #17
Source Project: pepper-robot-programming   Author: maverickjoy   File: asthama_search.py    License: MIT License 5 votes vote down vote up
def _transformTheta(self, theta):
        # CONVERTING THETA { THETA' % 360}
        if (float(theta) == math.radians(360)):
            theta = 0.0

        if (float(theta) == -(math.radians(360))):
            theta = 0.0

        if (float(theta) == math.radians(270)):
            theta = -math.pi/2

        if (float(theta) == -(math.radians(270))):
            theta = math.pi/2

        return theta 
Example #18
Source Project: torch-toolbox   Author: PistonY   File: functional.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _get_inverse_affine_matrix(center, angle, translate, scale, shear):
    # Helper method to compute inverse matrix for affine transformation

    angle = math.radians(angle)
    shear = math.radians(shear)
    M00 = math.cos(angle) * scale
    M01 = -math.sin(angle + shear) * scale
    M10 = math.sin(angle) * scale
    M11 = math.cos(angle + shear) * scale
    M02 = center[0] - center[0] * M00 - center[1] * M01 + translate[0]
    M12 = center[1] - center[0] * M10 - center[1] * M11 + translate[1]
    matrix = np.array([[M00, M01, M02], [M10, M11, M12]], dtype=np.float32)
    return matrix 
Example #19
Source Project: gw2pvo   Author: markruys   File: netatmo_api.py    License: MIT License 5 votes vote down vote up
def haversine_distance(self, lat1, lon1, lat2, lon2):
        R = 6371.0088
        lat1 = math.radians(lat1)
        lon1 = math.radians(lon1)
        lat2 = math.radians(lat2)
        lon2 = math.radians(lon2)
        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.atan2(math.sqrt(a), math.sqrt(1 - a))
        distance = R * c
        return distance * 1000 
Example #20
Source Project: pymesh   Author: taxpon   File: base.py    License: MIT License 5 votes vote down vote up
def rotate_x(self, deg):
        """Rotate mesh around x-axis

        :param float deg: Rotation angle (degree)
        :return:
        """
        rad = math.radians(deg)
        mat = numpy.array([
            [1, 0, 0, 0],
            [0, math.cos(rad), math.sin(rad), 0],
            [0, -math.sin(rad), math.cos(rad), 0],
            [0, 0, 0, 1]
        ])
        self.vectors = self.vectors.dot(mat)
        return self 
Example #21
Source Project: pymesh   Author: taxpon   File: base.py    License: MIT License 5 votes vote down vote up
def rotate_y(self, deg):
        """Rotate mesh around y-axis

        :param float deg: Rotation angle (degree)
        """
        rad = math.radians(deg)
        mat = numpy.array([
            [math.cos(rad), 0, -math.sin(rad), 0],
            [0, 1, 0, 0],
            [math.sin(rad), 0, math.cos(rad), 0],
            [0, 0, 0, 1]
        ])
        self.vectors = self.vectors.dot(mat)
        return self 
Example #22
Source Project: pymesh   Author: taxpon   File: base.py    License: MIT License 5 votes vote down vote up
def rotate_z(self, deg):
        """Rotate mesh around z-axis

        :param float deg: Rotation angle (degree)
        """
        rad = math.radians(deg)
        mat = numpy.array([
            [math.cos(rad), math.sin(rad), 0, 0],
            [-math.sin(rad), math.cos(rad), 0, 0],
            [0, 0, 1, 0],
            [0, 0, 0, 1]
        ])
        self.vectors = self.vectors.dot(mat)
        return self 
Example #23
Source Project: RingNet   Author: soubhiksanyal   File: renderer.py    License: MIT License 5 votes vote down vote up
def rotated(self,
                verts,
                deg,
                cam=None,
                axis='y',
                img=None,
                do_alpha=True,
                far=None,
                near=None,
                color_id=0,
                img_size=None):
        import math
        if axis == 'y':
            around = cv2.Rodrigues(np.array([0, math.radians(deg), 0]))[0]
        elif axis == 'x':
            around = cv2.Rodrigues(np.array([math.radians(deg), 0, 0]))[0]
        else:
            around = cv2.Rodrigues(np.array([0, 0, math.radians(deg)]))[0]
        center = verts.mean(axis=0)
        new_v = np.dot((verts - center), around) + center

        return self.__call__(
            new_v,
            cam,
            img=img,
            do_alpha=do_alpha,
            far=far,
            near=near,
            img_size=img_size,
            color_id=color_id) 
Example #24
Source Project: RingNet   Author: soubhiksanyal   File: renderer.py    License: MIT License 5 votes vote down vote up
def simple_renderer(rn,
                    verts,
                    faces,
                    yrot=np.radians(120),
                    color=colors['light_pink']):
    # Rendered model color
    rn.set(v=verts, f=faces, vc=color, bgcolor=np.ones(3))
    albedo = rn.vc

    # Construct Back Light (on back right corner)
    rn.vc = LambertianPointLight(
        f=rn.f,
        v=rn.v,
        num_verts=len(rn.v),
        light_pos=_rotateY(np.array([-200, -100, -100]), yrot),
        vc=albedo,
        light_color=np.array([1, 1, 1]))

    # Construct Left Light
    rn.vc += LambertianPointLight(
        f=rn.f,
        v=rn.v,
        num_verts=len(rn.v),
        light_pos=_rotateY(np.array([800, 10, 300]), yrot),
        vc=albedo,
        light_color=np.array([1, 1, 1]))

    # Construct Right Light
    rn.vc += LambertianPointLight(
        f=rn.f,
        v=rn.v,
        num_verts=len(rn.v),
        light_pos=_rotateY(np.array([-500, 500, 1000]), yrot),
        vc=albedo,
        light_color=np.array([.7, .7, .7]))

    return rn.r 
Example #25
Source Project: dronekit-python   Author: dronekit   File: set_attitude_target.py    License: Apache License 2.0 5 votes vote down vote up
def send_attitude_target(roll_angle = 0.0, pitch_angle = 0.0,
                         yaw_angle = None, yaw_rate = 0.0, use_yaw_rate = False,
                         thrust = 0.5):
    """
    use_yaw_rate: the yaw can be controlled using yaw_angle OR yaw_rate.
                  When one is used, the other is ignored by Ardupilot.
    thrust: 0 <= thrust <= 1, as a fraction of maximum vertical thrust.
            Note that as of Copter 3.5, thrust = 0.5 triggers a special case in
            the code for maintaining current altitude.
    """
    if yaw_angle is None:
        # this value may be unused by the vehicle, depending on use_yaw_rate
        yaw_angle = vehicle.attitude.yaw
    # Thrust >  0.5: Ascend
    # Thrust == 0.5: Hold the altitude
    # Thrust <  0.5: Descend
    msg = vehicle.message_factory.set_attitude_target_encode(
        0, # time_boot_ms
        1, # Target system
        1, # Target component
        0b00000000 if use_yaw_rate else 0b00000100,
        to_quaternion(roll_angle, pitch_angle, yaw_angle), # Quaternion
        0, # Body roll rate in radian
        0, # Body pitch rate in radian
        math.radians(yaw_rate), # Body yaw rate in radian/second
        thrust  # Thrust
    )
    vehicle.send_mavlink(msg) 
Example #26
Source Project: sphere   Author: qedus   File: sphere.py    License: MIT License 5 votes vote down vote up
def __init__(self, radians=0):
        if not isinstance(radians, (long, float, int)):
            raise ValueError()
        self.__radians = radians 
Example #27
Source Project: sphere   Author: qedus   File: sphere.py    License: MIT License 5 votes vote down vote up
def from_degrees(cls, degrees):
        return cls(math.radians(degrees)) 
Example #28
Source Project: sphere   Author: qedus   File: sphere.py    License: MIT License 5 votes vote down vote up
def from_radians(cls, radians):
        return cls(radians) 
Example #29
Source Project: sphere   Author: qedus   File: sphere.py    License: MIT License 5 votes vote down vote up
def radians(self):
        return self.__radians 
Example #30
Source Project: sphere   Author: qedus   File: sphere.py    License: MIT License 5 votes vote down vote up
def from_degrees(cls, lat, lon):
        return cls(math.radians(lat), math.radians(lon))