Python math.radians() Examples

The following are code examples for showing how to use math.radians(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: L.E.S.M.A   Author: NatanaelAntonioli   File: L.E.S.M.A. - Fabrica de Noobs Speedtest.py    Apache License 2.0 7 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 2
Project: AboveTustin   Author: kevinabrandon   File: geomath.py    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 3
Project: pepper-robot-programming   Author: maverickjoy   File: asthama_search.py    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 4
Project: streetview_objectmapping   Author: vlkryl   File: objectmapping.py    MIT License 6 votes vote down vote up
def haversine(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(radians, [lon1, lat1, lon2, lat2])
    # haversine formula 
    dlon = lon2 - lon1 
    dlat = lat2 - lat1 
    a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
    c = 2 * asin(sqrt(a)) 
    m = 6367000. * c
    return m

# calculating the intersection  point between two rays (specified each by camera position and depth-estimated object location) 
Example 5
Project: airqdata   Author: dr-1   File: utils.py    GNU General Public License v3.0 6 votes vote down vote up
def haversine(lat1, lon1, lat2, lon2):
    """Calculate the great circle distance between two points on earth.

    Args:
        lat1, lon1, lat2, lon2: coordinates of point 1 and point 2 in
            decimal degrees

    Returns:
        Distance in kilometers
    """

    # Convert decimal degrees to radians
    lat1, lon1, lat2, lon2 = (radians(val) for val in (lat1, lon1, lat2, lon2))

    # Haversine formula
    d_lat = lat2 - lat1
    d_lon = lon2 - lon1
    a = sin(d_lat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(d_lon / 2) ** 2
    c = 2 * asin(sqrt(a))
    radius = 6371  # Radius of earth in kilometers
    distance = c * radius

    return distance 
Example 6
Project: symbolator   Author: kevinpt   File: shapes.py    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 7
Project: symbolator   Author: kevinpt   File: cairo_backend.py    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 8
Project: ngo-addons-backport   Author: camptocamp   File: pdf.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def mergeRotatedScaledPage(self, page2, rotation, scale):
        rotation = math.radians(rotation)
        rotating = [[math.cos(rotation), math.sin(rotation),0],
                    [-math.sin(rotation),math.cos(rotation), 0],
                    [0,                  0,                  1]]
        scaling = [[scale,0,    0],
                   [0,    scale,0],
                   [0,    0,    1]]
        ctm = utils.matrixMultiply(rotating, scaling)

        return self.mergeTransformedPage(page2,
                                         [ctm[0][0], ctm[0][1],
                                          ctm[1][0], ctm[1][1],
                                          ctm[2][0], ctm[2][1]])

    ##
    # This is similar to mergePage, but the stream to be merged is translated
    # and scaled by appling a transformation matrix.
    #
    # @param page2 An instance of {@link #PageObject PageObject} to be merged.
    # @param scale The scaling factor
    # @param tx    The translation on X axis
    # @param tx    The translation on Y axis 
Example 9
Project: ngo-addons-backport   Author: camptocamp   File: pdf.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def mergeRotatedScaledTranslatedPage(self, page2, rotation, scale, tx, ty):
        translation = [[1, 0, 0],
                       [0, 1, 0],
                       [tx,ty,1]]
        rotation = math.radians(rotation)
        rotating = [[math.cos(rotation), math.sin(rotation),0],
                    [-math.sin(rotation),math.cos(rotation), 0],
                    [0,                  0,                  1]]
        scaling = [[scale,0,    0],
                   [0,    scale,0],
                   [0,    0,    1]]
        ctm = utils.matrixMultiply(rotating, scaling)
        ctm = utils.matrixMultiply(ctm, translation)

        return self.mergeTransformedPage(page2, [ctm[0][0], ctm[0][1],
                                                 ctm[1][0], ctm[1][1],
                                                 ctm[2][0], ctm[2][1]])

    ##
    # Applys a transformation matrix the page.
    #
    # @param ctm   A 6 elements tuple containing the operands of the
    #              transformation matrix 
Example 10
Project: QPong   Author: HuangJunye   File: ball.py    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 11
Project: graph-keyword-search   Author: usc-isi-i2   File: util.py    Apache License 2.0 6 votes vote down vote up
def haversine(lon1, lat1, lon2, lat2, unit='mi'):
    """
    Calculate the great circle distance between two points 
    on the earth (specified in decimal degrees)
    """
    # convert decimal degrees to radians 
    lon1, lat1, lon2, lat2 = list(map(radians, [lon1, lat1, lon2, lat2]))
    # haversine formula 
    dlon = lon2 - lon1 
    dlat = lat2 - lat1 
    # print "dlat=%r,dlon=%r" % (dlat, dlon)
    a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
    c = 2 * asin(sqrt(a)) 
    
    distance = {'km': 6367,
                'mi': 3956,
                'ft': 20889110}[unit] * c
    return distance


# brought in from context.py r23462 
Example 12
Project: TripInference   Author: SUTDMEC   File: getActivities.py    MIT License 6 votes vote down vote up
def great_circle_dist(a, b, unit="kilometers"):
    """
    compute great circle distance between two latitude/longitude coordinate pairs.
    Returns great cirlce distance in kilometers (default) or meters.
    https://en.wikipedia.org/wiki/Great-circle_distance
    """
    lat1, lon1 = a
    lat2, lon2 = b
    if (lat1==92) or (lat2==92):
        return -1 # invalid location gives invalid distance
    dlat = math.radians(lat2 - lat1)
    dlon = math.radians(lon2 - lon1)
    a = (math.sin(dlat / 2.0) * math.sin(dlat / 2.0) +
            math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * 
            math.sin(dlon / 2.0) * math.sin(dlon / 2.0))
    c = 2.0 * math.asin(math.sqrt(a))
    dist_km = earth_radius * c
    if unit == "kilometers":
        return dist_km
    elif unit == "meters":
        return dist_km * 1000
    else:
        raise ValueError("Unknown unit: %s" % unit) 
Example 13
Project: ssrspeed_backup   Author: mazhenting   File: speedtestnet.py    GNU General Public License v3.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 14
Project: carla_py   Author: IamWangYunKai   File: misc.py    MIT License 6 votes vote down vote up
def is_within_distance_ahead(target_location, current_location, orientation, max_distance):
    """
    Check if a target object is within a certain distance in front of a reference object.

    :param target_location: location of the target object
    :param current_location: location of the reference object
    :param orientation: orientation of the reference object
    :param max_distance: maximum allowed distance
    :return: True if target object is within max_distance ahead of the reference object
    """
    target_vector = np.array([target_location.x - current_location.x, target_location.y - current_location.y])
    norm_target = np.linalg.norm(target_vector)

    # If the vector is too short, we can simply stop here
    if norm_target < 0.001:
        return True

    if norm_target > max_distance:
        return False

    forward_vector = np.array(
        [math.cos(math.radians(orientation)), math.sin(math.radians(orientation))])
    d_angle = math.degrees(math.acos(np.dot(forward_vector, target_vector) / norm_target))

    return d_angle < 90.0 
Example 15
Project: carla_py   Author: IamWangYunKai   File: misc.py    MIT License 6 votes vote down vote up
def compute_magnitude_angle(target_location, current_location, orientation):
    """
    Compute relative angle and distance between a target_location and a current_location

    :param target_location: location of the target object
    :param current_location: location of the reference object
    :param orientation: orientation of the reference object
    :return: a tuple composed by the distance to the object and the angle between both objects
    """
    target_vector = np.array([target_location.x - current_location.x, target_location.y - current_location.y])
    norm_target = np.linalg.norm(target_vector)

    forward_vector = np.array([math.cos(math.radians(orientation)), math.sin(math.radians(orientation))])
    d_angle = math.degrees(math.acos(np.dot(forward_vector, target_vector) / norm_target))

    return (norm_target, d_angle) 
Example 16
Project: carla_py   Author: IamWangYunKai   File: misc.py    MIT License 6 votes vote down vote up
def is_within_distance_ahead(target_location, current_location, orientation, max_distance):
    """
    Check if a target object is within a certain distance in front of a reference object.

    :param target_location: location of the target object
    :param current_location: location of the reference object
    :param orientation: orientation of the reference object
    :param max_distance: maximum allowed distance
    :return: True if target object is within max_distance ahead of the reference object
    """
    target_vector = np.array([target_location.x - current_location.x, target_location.y - current_location.y])
    norm_target = np.linalg.norm(target_vector)

    # If the vector is too short, we can simply stop here
    if norm_target < 0.001:
        return True

    if norm_target > max_distance:
        return False

    forward_vector = np.array(
        [math.cos(math.radians(orientation)), math.sin(math.radians(orientation))])
    d_angle = math.degrees(math.acos(np.dot(forward_vector, target_vector) / norm_target))

    return d_angle < 90.0 
Example 17
Project: carla_py   Author: IamWangYunKai   File: misc.py    MIT License 6 votes vote down vote up
def compute_magnitude_angle(target_location, current_location, orientation):
    """
    Compute relative angle and distance between a target_location and a current_location

    :param target_location: location of the target object
    :param current_location: location of the reference object
    :param orientation: orientation of the reference object
    :return: a tuple composed by the distance to the object and the angle between both objects
    """
    target_vector = np.array([target_location.x - current_location.x, target_location.y - current_location.y])
    norm_target = np.linalg.norm(target_vector)

    forward_vector = np.array([math.cos(math.radians(orientation)), math.sin(math.radians(orientation))])
    d_angle = math.degrees(math.acos(np.dot(forward_vector, target_vector) / norm_target))

    return (norm_target, d_angle) 
Example 18
Project: carla_py   Author: IamWangYunKai   File: misc.py    MIT License 6 votes vote down vote up
def is_within_distance_ahead(target_location, current_location, orientation, max_distance):
    """
    Check if a target object is within a certain distance in front of a reference object.

    :param target_location: location of the target object
    :param current_location: location of the reference object
    :param orientation: orientation of the reference object
    :param max_distance: maximum allowed distance
    :return: True if target object is within max_distance ahead of the reference object
    """
    target_vector = np.array([target_location.x - current_location.x, target_location.y - current_location.y])
    norm_target = np.linalg.norm(target_vector)

    # If the vector is too short, we can simply stop here
    if norm_target < 0.001:
        return True

    if norm_target > max_distance:
        return False

    forward_vector = np.array(
        [math.cos(math.radians(orientation)), math.sin(math.radians(orientation))])
    d_angle = math.degrees(math.acos(np.dot(forward_vector, target_vector) / norm_target))

    return d_angle < 90.0 
Example 19
Project: carla_py   Author: IamWangYunKai   File: misc.py    MIT License 6 votes vote down vote up
def is_within_distance_ahead(target_location, current_location, orientation, max_distance):
    """
    Check if a target object is within a certain distance in front of a reference object.

    :param target_location: location of the target object
    :param current_location: location of the reference object
    :param orientation: orientation of the reference object
    :param max_distance: maximum allowed distance
    :return: True if target object is within max_distance ahead of the reference object
    """
    target_vector = np.array([target_location.x - current_location.x, target_location.y - current_location.y])
    norm_target = np.linalg.norm(target_vector)

    # If the vector is too short, we can simply stop here
    if norm_target < 0.001:
        return True

    if norm_target > max_distance:
        return False

    forward_vector = np.array(
        [math.cos(math.radians(orientation)), math.sin(math.radians(orientation))])
    d_angle = math.degrees(math.acos(np.dot(forward_vector, target_vector) / norm_target))

    return d_angle < 90.0 
Example 20
Project: carla_py   Author: IamWangYunKai   File: misc.py    MIT License 6 votes vote down vote up
def compute_magnitude_angle(target_location, current_location, orientation):
    """
    Compute relative angle and distance between a target_location and a current_location

    :param target_location: location of the target object
    :param current_location: location of the reference object
    :param orientation: orientation of the reference object
    :return: a tuple composed by the distance to the object and the angle between both objects
    """
    target_vector = np.array([target_location.x - current_location.x, target_location.y - current_location.y])
    norm_target = np.linalg.norm(target_vector)

    forward_vector = np.array([math.cos(math.radians(orientation)), math.sin(math.radians(orientation))])
    d_angle = math.degrees(math.acos(np.dot(forward_vector, target_vector) / norm_target))

    return (norm_target, d_angle) 
Example 21
Project: honeybee   Author: ladybug-tools   File: room.py    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 22
Project: toolbox   Author: aschaller   File: gui.py    GNU General Public License v3.0 6 votes vote down vote up
def OnChamferAngleUnit(self, event):
        oldUnit = self.chamferCfgSettings.angleUnit
        newUnit = str(self.chamferUnitwxChoice.GetSelection())

        if oldUnit == '0' and newUnit == '1':
            # deg to rad
            self.chamferAngleSpinCtrlDouble.SetMax(1.5708)
            self.chamferAngleSpinCtrlDouble.SetValue(m.radians(self.chamferAngleSpinCtrlDouble.GetValue()))
            self.chamferAngleSpinCtrlDouble.SetIncrement(0.01)
            self.chamferCfgSettings.angleUnit = '1'
        elif oldUnit == '1' and newUnit == '0':
            # rad to deg
            self.chamferAngleSpinCtrlDouble.SetMax(90)
            self.chamferAngleSpinCtrlDouble.SetValue(round(m.degrees(self.chamferAngleSpinCtrlDouble.GetValue()), 2))
            self.chamferAngleSpinCtrlDouble.SetIncrement(1)
            self.chamferCfgSettings.angleUnit = '0'

        self.OnChamferSpinCtrlDouble(None) 
Example 23
Project: opencv_transforms   Author: jbohnslav   File: functional.py    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 24
Project: LaserTOF   Author: kyleuckert   File: backend_agg.py    MIT License 6 votes vote down vote up
def draw_tex(self, gc, x, y, s, prop, angle, ismath='TeX!', mtext=None):
        # todo, handle props, angle, origins
        size = prop.get_size_in_points()

        texmanager = self.get_texmanager()

        Z = texmanager.get_grey(s, size, self.dpi)
        Z = np.array(Z * 255.0, np.uint8)

        w, h, d = self.get_text_width_height_descent(s, prop, ismath)
        xd = d * sin(radians(angle))
        yd = d * cos(radians(angle))
        x = np.round(x + xd)
        y = np.round(y + yd)

        self._renderer.draw_text_image(Z, x, y, angle, gc) 
Example 25
Project: tmx2map   Author: joshuaskelly   File: mathhelper.py    MIT License 5 votes vote down vote up
def rotation_matrix(degrees):
        angle = math.radians(degrees)
        return numpy.array((
            (math.cos(angle), -math.sin(angle), 0.0, 0.0),
            (math.sin(angle), math.cos(angle), 0.0, 0.0),
            (0.0, 0.0, 1.0, 0.0),
            (0.0, 0.0, 0.0, 1.0)
        )) 
Example 26
Project: tmx2map   Author: joshuaskelly   File: mathhelper.py    MIT License 5 votes vote down vote up
def vector_from_angle(degrees):
    """Returns a unit vector in the xy-plane rotated by the given degrees from
    the positive x-axis"""
    radians = math.radians(degrees)
    z_rot_matrix = numpy.identity(4)
    z_rot_matrix[0, 0] = math.cos(radians)
    z_rot_matrix[0, 1] = -math.sin(radians)
    z_rot_matrix[1, 0] = math.sin(radians)
    z_rot_matrix[1, 1] = math.cos(radians)

    return tuple(numpy.dot(z_rot_matrix, (1, 0, 0, 0))[:3]) 
Example 27
Project: pepper-robot-programming   Author: maverickjoy   File: asthama_search.py    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 28
Project: client   Author: Scorched-Moon   File: ani.py    GNU General Public License v3.0 5 votes vote down vote up
def image_rotate(tv,name,img,shape,angles,diff=0):
    """Rotate an image and put it into tv.images
    
    Arguments:
        tv -- vid to load into
        name -- prefix name to give the images
        image -- image to load anis from
        shape -- shape fimage (usually a subset of 0,0,w,h) used for collision detection
        angles -- a list of angles to render in degrees
        diff -- a number to add to the angles, to correct for source image not actually being at 0 degrees

    """
    w1,h1 = img.get_width(),img.get_height()
    shape = pygame.Rect(shape)
    ps = shape.topleft,shape.topright,shape.bottomleft,shape.bottomright
    for a in angles:
        img2 = pygame.transform.rotate(img,a+diff)
        w2,h2 = img2.get_width(),img2.get_height()
        minx,miny,maxx,maxy = 1024,1024,0,0
        for x,y in ps:
            x,y = x-w1/2,y-h1/2
            a2 = math.radians(a+diff)
            #NOTE: the + and - are switched from the normal formula because of
            #the weird way that pygame does the angle...
            x2 = x*math.cos(a2) + y*math.sin(a2) 
            y2 = y*math.cos(a2) - x*math.sin(a2)
            x2,y2 = x2+w2/2,y2+h2/2
            minx = min(minx,x2)
            miny = min(miny,y2)
            maxx = max(maxx,x2)
            maxy = max(maxy,y2)
        r = pygame.Rect(minx,miny,maxx-minx,maxy-miny)
        #((ww-w)/2,(hh-h)/2,w,h)
        tv.images["%s.%d"%(name,a)] = img2,r 
Example 29
Project: pyblish-win   Author: pyblish   File: test_math.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testRadians(self):
        self.assertRaises(TypeError, math.radians)
        self.ftest('radians(180)', math.radians(180), math.pi)
        self.ftest('radians(90)', math.radians(90), math.pi/2)
        self.ftest('radians(-45)', math.radians(-45), -math.pi/4) 
Example 30
Project: bedset   Author: bonjorno7   File: menus.py    GNU General Public License v3.0 5 votes vote down vote up
def draw(self, context):
        pie = self.layout.menu_pie()
        pie.separator()
        pie.separator()
        pie.operator("mesh.customdata_custom_splitnormals_clear", text="Clear Custom Normals")
        pie.operator(AutoSmooth.bl_idname, text="Auto Smooth 60").angle = math.radians(60)
        pie.operator(AutoSmooth.bl_idname, text="Auto Smooth 30").angle = math.radians(30)
        pie.operator(AutoSmooth.bl_idname, text="Auto Smooth 180").angle = math.radians(180)
        pie.operator("object.shade_flat", text="Shade Flat")
        pie.operator("object.shade_smooth", text="Shade Smooth") 
Example 31
Project: kuaa   Author: rafaelwerneck   File: application.py    GNU General Public License v3.0 5 votes vote down vote up
def show_block_wheel(self):
        """Shows the block wheel for the user to choose a block to add in the
        experiment."""
        # If first time showing the wheel, simply remove the background guide
        # text
        if self._textID:
            self.canvas.delete(self._textID)
            self._textID = None

        self._afterjob = None
        self._wheel_visible = True

        # Gray out everything else
        for block in self._experiment_blocks:
            block.gray_out()
            if block._context_visible:
                block._context_box.set_invisible()
                block._context_visible = False

        self.canvas.configure(bg='#444444')

        # Display the wheel
        total_blocks = len(config.APPLICATION_BLOCKS)
        for i in xrange(total_blocks):
            teta = math.radians(i * (float(360) / total_blocks))
            self._wheel_blocks[i].set_visible()
            self._wheel_blocks[i].position(self._button_press_position['x'] -
                                           (config.BLOCK_SIZE / 2) +
                                           (config.WHEEL_RADIUS *
                                            math.sin(teta)),
                                           self._button_press_position['y'] -
                                           (config.BLOCK_SIZE / 2) -
                                           (config.WHEEL_RADIUS *
                                            math.cos(teta)))
            tk.Misc.lift(self._wheel_blocks[i]._frame) 
Example 32
Project: look_around   Author: iqbalhusen   File: haversine.py    MIT License 5 votes vote down vote up
def distance(origin, destination):
    """
    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(radians, origin + destination)

    # Haversine formula
    dlon = lon2 - lon1 
    dlat = lat2 - lat1 
    a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
    c = 2 * asin(sqrt(a)) 
    r = 6371  # Radius of earth in kilometers. Use 3956 for miles
    return c * r 
Example 33
Project: spqrel_tools   Author: LCAS   File: xapparser.py    MIT License 5 votes vote down vote up
def _makeJointDict(motors, use_radians = True):
    pose = {}
    for p in motors.findall(NS + "Motor"):
        name = p.find(NS + 'name').text
        value = float(p.find(NS + 'value').text)
        if not use_radians:
            value = math.radians(value)

        pose[name] = value

    return pose 
Example 34
Project: spqrel_tools   Author: LCAS   File: xapparser.py    MIT License 5 votes vote down vote up
def getpostures(xap_file):
    """ Parses a Aldebaran Choregraphe posture library (.xap files)
    into a Python dictionary of postures.
    """

    if not os.path.exists(xap_file):
        raise RuntimeError("The XAP file %s does not exist." % xap_file)

    try:
        tree = ET.parse(xap_file)
    except ET.ParseError:
        raise RuntimeError("The XAP file %s is not a valid XML file." % xap_file)


    root=tree.getroot()

    postures = {}


    positions = [p for p in root.iter(NS + 'position')]

    if not positions:
        raise RuntimeError("The XAP file %s does not contain any pose." % xap_file)

    for p in positions:
        name = p.find(NS + 'name').text
        version = p.find(NS + 'version') # it *seems* that the 'version' 2 indicates joints stored in radians
        pose = _makeJointDict(p.find(NS + "Motors"), version is not None and version.text=='2')

        postures[name] = pose

    return postures 
Example 35
Project: o2g   Author: hiposfer   File: gtfs_dummy.py    MIT License 5 votes vote down vote up
def haversine(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(radians, [lon1, lat1, lon2, lat2])

    # haversine formula
    dlon = lon2 - lon1
    dlat = lat2 - lat1
    a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2
    c = 2 * asin(sqrt(a))
    r = 6371  # Radius of earth in kilometers. Use 3956 for miles
    return c * r 
Example 36
Project: NAO   Author: AISTLAB   File: wsNaoVisionMT.py    MIT License 5 votes vote down vote up
def getGroundPointDistance(self,x,y,pitchang):
    xdist=0
    ydist=0
    angle=math.radians(47.64*(y-self.IMGH/2)/self.IMGH+39.7)+0.18+pitchang #上下视角
    h=45+5*math.sin(-pitchang)
    ydist=h/math.tan(angle)
    if ydist<100:ydist-=3 #修正系数,测试出来的数据
    if self._robotip=="192.168.1.103": #两个机器人部分参数不同,修正,nao y值加6cm
      ydist+=5
    wangle=math.radians(60.97*(x-160)/320.0) #左右视角
    xdist=math.sqrt(ydist*ydist+h**2)*math.tan(wangle) #下摄像头高度45+修正值
    xdist=round(xdist,2)
    ydist=round(ydist,2)
    return xdist,ydist 
Example 37
Project: NAO   Author: AISTLAB   File: wsNaoVisionMT.py    MIT License 5 votes vote down vote up
def getSpaceBallDistance(self):
    thresh=self._threshBall.copy() #保护
    (x,y),r=self.getMinCircle(thresh)
    dist=0
    if r>0: #缩放转换函数
      dist=round(self._baseSize*0.054/math.atan(math.radians(47.64*r/self.IMGH)),2)
      if dist>50:dist*=1.1
    return dist 
Example 38
Project: NAO   Author: AISTLAB   File: kickState.py    MIT License 5 votes vote down vote up
def do(self,nv,nm):
        print "modify."
        nm.poseInit()
        nm.headPitchTo(nm.MAX_HEADPITCH)
        time.sleep(0.5)
        x,y=nv.getGroundBallDistance(nm.getHeadPitchAngle())
        print x,y
        if y>0:
            nm._motion.walkTo((y-10)/100.0,-x/100.0,0,\
            [["MaxStepFrequency", 0.2]])
            if self.ballLocation==0:
                print "mid turn"
                nm._motion.walkTo(0,0,math.radians((random.randint(0,1)*2-1)*20))
            self.__class__=self.nextstate 
Example 39
Project: NAO   Author: AISTLAB   File: kickState.py    MIT License 5 votes vote down vote up
def do(self,nv,nm):
        "finding gate."
        nm.headPitchTo(nm.MIN_HEADPITCH)
        time.sleep(1)
        x,y,w,h=nv._gateBounding
        print x,w
        if x<5 and w<200:
            nm._motion.walkTo(0,0,math.radians(10))
        elif x>30 and w<200:
            nm._motion.walkTo(0,0,math.radians(-10))
        else:
            self.__class__=self.nextstate 
Example 40
Project: deep-nn-car   Author: scope-lab-vu   File: PluggableFeatures.py    MIT License 5 votes vote down vote up
def updatePositionAndHeading(self,deltaX,deltaTheta):
        if (deltaX>0.0):
            self.totalDistanceCovered = deltaX + self.totalDistanceCovered
            self.heading = self.heading + deltaTheta
            self.heading = self.heading%360
            headingInRadians = math.radians(self.heading) # converts degrees to radians
            self.x = self.x + deltaX*math.cos(headingInRadians)
            self.y = self.y + deltaX*math.sin(headingInRadians) 
Example 41
Project: directional_drilling_calculations   Author: BrettMontague   File: drillingcalcs.py    MIT License 5 votes vote down vote up
def vertical_section_calc(northing: float, easting: float,
                          vertical_section_difference: float
                          ) -> Tuple[float, float, float, float]:
    ''' 
    using northing, easting and vertical section direction as inputs 
    and return directional difference, closure distance, closure azimuth
    , vertical section difference (vsd). 
    '''

    # Calculation for closure distance
    closure_distance = (northing**2 + easting**2)**.5

    # Calculation for closure azimuth
    if northing == 0:
        closure_azimuth = 0
    else:
        closure_azimuth = math.degrees(np.arctan(easting / northing))

    # Calculation for directional difference
    directional_difference = closure_azimuth - vertical_section_difference

    # Calculation for vertical section
    vertical_section = (closure_distance * (np.cos(
        math.radians(vertical_section_difference - closure_azimuth))))

    return directional_difference, closure_distance, closure_azimuth, vertical_section 
Example 42
Project: MeteorTracker   Author: heidtn   File: match_events.py    MIT License 5 votes vote down vote up
def distanceBetweenCoords(lat1, lon1, lat2, lon2):
    """
    This uses the haversine formula to calculate the great-circle distance
    between two points.

    Parameters
    ----------
    lat1 : float
        The latitude of the first point
    lon1 : float
        The longitude of the first point
    lat2 : float
        The latitude of the second point
    lon2 : float
        The longitude of the second point
    """
    earthRadius = 6371.0  # earths radius in km
    phi1 = math.radians(lat1)
    phi2 = math.radians(lat2)
    deltaPhi = math.radians(lat2 - lat1)
    deltaLambda = math.radians(lon2 - lon1)

    a = math.sin(deltaPhi/2.0)**2 + \
                 math.cos(phi1)*math.cos(phi2)*(math.sin(deltaLambda/2.0)**2)

    c = 2.0*math.atan2(math.sqrt(a), math.sqrt(1 - a))
    d = earthRadius*c

    return d 
Example 43
Project: RLBotPack   Author: RLBot   File: util.py    MIT License 5 votes vote down vote up
def can_dodge(agent, target):
    bot_to_target = target - agent.info.my_car.pos
    local_bot_to_target = dot(bot_to_target, agent.info.my_car.theta)
    angle_front_to_target = math.atan2(local_bot_to_target[1], local_bot_to_target[0])
    distance_bot_to_target = norm(vec2(bot_to_target))
    good_angle = math.radians(-10) < angle_front_to_target < math.radians(10)
    on_ground = agent.info.my_car.on_ground and agent.info.my_car.pos[2] < 100
    going_fast = velocity_2d(agent.info.my_car.vel) > 1250
    target_not_in_goal = not agent.info.my_goal.inside(target)
    return good_angle and distance_bot_to_target > 2000 and on_ground and going_fast and target_not_in_goal 
Example 44
Project: RLBotPack   Author: RLBot   File: shooting.py    MIT License 5 votes vote down vote up
def should_dodge(agent):
    car = agent.info.my_car
    their_goal = agent.info.their_goal
    close_to_goal = distance_2d(car.pos, their_goal.center) < 4000
    aiming_for_goal = abs(line_backline_intersect(their_goal.center[1], vec2(car.pos), vec2(car.forward()))) < 850
    bot_to_target = agent.info.ball.pos - car.pos
    local_bot_to_target = dot(bot_to_target, agent.info.my_car.theta)
    angle_front_to_target = math.atan2(local_bot_to_target[1], local_bot_to_target[0])
    close_to_ball = norm(vec2(bot_to_target)) < 850
    good_angle = math.radians(-10) < angle_front_to_target < math.radians(10)
    return close_to_ball and close_to_goal and aiming_for_goal and good_angle 
Example 45
Project: FreeCAD-Lithophane   Author: furti   File: geometry_utils.py    MIT License 5 votes vote down vote up
def pointOnCircle(radius, angle):
  angleInRadians = math.radians(angle)

  x = radius * math.sin(angleInRadians)
  y = radius * math.cos(angleInRadians)

  return (x, y) 
Example 46
Project: blender-tools   Author: vvoovv   File: osm_georeferencing.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, **kwargs):
        # setting default values
        self.lat = 0. # in degrees
        self.lon = 0. # in degrees
        self.k = 1. # scale factor
        
        for attr in kwargs:
            setattr(self, attr, kwargs[attr])
        self.latInRadians = math.radians(self.lat) 
Example 47
Project: blender-tools   Author: vvoovv   File: osm_georeferencing.py    GNU General Public License v3.0 5 votes vote down vote up
def fromGeographic(self, lat, lon):
        lat = math.radians(lat)
        lon = math.radians(lon-self.lon)
        B = math.sin(lon) * math.cos(lat)
        x = 0.5 * self.k * self.radius * math.log((1.+B)/(1.-B))
        y = self.k * self.radius * ( math.atan(math.tan(lat)/math.cos(lon)) - self.latInRadians )
        return (x,y) 
Example 48
Project: torch-toolbox   Author: PistonY   File: functional.py    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 49
Project: ngo-addons-backport   Author: camptocamp   File: pdf.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def mergeRotatedPage(self, page2, rotation):
        rotation = math.radians(rotation)
        return self.mergeTransformedPage(page2,
            [math.cos(rotation),  math.sin(rotation),
             -math.sin(rotation), math.cos(rotation),
             0,                   0])

    ##
    # This is similar to mergePage, but the stream to be merged is translated
    # by appling a transformation matrix.
    #
    # @param page2 An instance of {@link #PageObject PageObject} to be merged.
    # @param tx    The translation on X axis
    # @param tx    The translation on Y axis 
Example 50
Project: pymesh   Author: taxpon   File: base.py    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 51
Project: pymesh   Author: taxpon   File: base.py    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 52
Project: pymesh   Author: taxpon   File: base.py    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 53
Project: RingNet   Author: soubhiksanyal   File: renderer.py    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 54
Project: RingNet   Author: soubhiksanyal   File: renderer.py    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 55
Project: openrocketdoc   Author: open-aerospace   File: document.py    GNU General Public License v3.0 5 votes vote down vote up
def sweep(self):
        """**[m]** The Distance from the start of the fin to the beginning of
        the tip.
        """
        if self._sweep is not None:
            return self._sweep
        return self.span * tan(radians(self._sweepangle)) 
Example 56
Project: TripInference   Author: SUTDMEC   File: getActivities.py    MIT License 5 votes vote down vote up
def distance_on_earth(lat1, lon1, lat2, lon2):
    #print "starting distance comp ",lat1,lon1,lat2,lon2
    if lat1==lat2 and lon1==lon2:
        return 0.0
    
    # Convert latitude and longitude to 
    # spherical coordinates in radians.
    degrees_to_radians = math.pi/180.0
         
    # phi = 90 - latitude
    phi1 = (90.0 - lat1)*degrees_to_radians
    phi2 = (90.0 - lat2)*degrees_to_radians
         
    # theta = longitude
    theta1 = lon1*degrees_to_radians
    theta2 = lon2*degrees_to_radians
    # Compute spherical distance from spherical coordinates.
         
    # For two locations in spherical coordinates 
    # (1, theta, phi) and (1, theta, phi)
    # cosine( arc length ) = 
    #    sin phi sin phi' cos(theta-theta') + cos phi cos phi'
    # distance = rho * arc length
     
    cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) + 
           math.cos(phi1)*math.cos(phi2))
    #print type(cos)
    try:
        arc = math.acos( cos )
    except ValueError:
        arc = 1.0/6371/1000
    #print arc
    # Distance in meters
    return arc*6371*1000 
Example 57
Project: exposure   Author: yuanming-hu   File: util.py    MIT License 5 votes vote down vote up
def largest_rotated_rect(w, h, angle):
  """
    Given a rectangle of size wxh that has been rotated by 'angle' (in
    radians), computes the width and height of the largest possible
    axis-aligned rectangle within the rotated rectangle.

    Original JS code by 'Andri' and Magnus Hoff from Stack Overflow

    Converted to Python by Aaron Snoswell
    """

  quadrant = int(math.floor(angle / (math.pi / 2))) & 3
  sign_alpha = angle if ((quadrant & 1) == 0) else math.pi - angle
  alpha = (sign_alpha % math.pi + math.pi) % math.pi

  bb_w = w * math.cos(alpha) + h * math.sin(alpha)
  bb_h = w * math.sin(alpha) + h * math.cos(alpha)

  gamma = math.atan2(bb_w, bb_w) if (w < h) else math.atan2(bb_w, bb_w)

  delta = math.pi - alpha - gamma

  length = h if (w < h) else w

  d = length * math.cos(alpha)
  a = d * math.sin(alpha) / math.sin(delta)

  y = a * math.cos(gamma)
  x = y * math.tan(gamma)

  return (bb_w - 2 * x, bb_h - 2 * y) 
Example 58
Project: exposure   Author: yuanming-hu   File: util.py    MIT License 5 votes vote down vote up
def rotate_and_crop(image, angle):
  image_width, image_height = image.shape[:2]
  image_rotated = rotate_image(image, angle)
  image_rotated_cropped = crop_around_center(image_rotated,
                                             *largest_rotated_rect(
                                                 image_width, image_height,
                                                 math.radians(angle)))
  return image_rotated_cropped 
Example 59
Project: carla_py   Author: IamWangYunKai   File: misc.py    MIT License 5 votes vote down vote up
def draw_waypoints(world, waypoints, z=0.5):
    """
    Draw a list of waypoints at a certain height given in z.

    :param world: carla.world object
    :param waypoints: list or iterable container with the waypoints to draw
    :param z: height in meters
    :return:
    """
    for w in waypoints:
        t = w.transform
        begin = t.location + carla.Location(z=z)
        angle = math.radians(t.rotation.yaw)
        end = begin + carla.Location(x=math.cos(angle), y=math.sin(angle))
        world.debug.draw_arrow(begin, end, arrow_size=0.3, life_time=1.0) 
Example 60
Project: carla_py   Author: IamWangYunKai   File: misc.py    MIT License 5 votes vote down vote up
def draw_waypoints(world, waypoints, z=0.5):
    """
    Draw a list of waypoints at a certain height given in z.

    :param world: carla.world object
    :param waypoints: list or iterable container with the waypoints to draw
    :param z: height in meters
    :return:
    """
    for w in waypoints:
        t = w.transform
        begin = t.location + carla.Location(z=z)
        angle = math.radians(t.rotation.yaw)
        end = begin + carla.Location(x=math.cos(angle), y=math.sin(angle))
        world.debug.draw_arrow(begin, end, arrow_size=0.3, life_time=1.0) 
Example 61
Project: carla_py   Author: IamWangYunKai   File: misc.py    MIT License 5 votes vote down vote up
def draw_waypoints(world, waypoints, z=0.5):
    """
    Draw a list of waypoints at a certain height given in z.

    :param world: carla.world object
    :param waypoints: list or iterable container with the waypoints to draw
    :param z: height in meters
    :return:
    """
    for w in waypoints:
        t = w.transform
        begin = t.location + carla.Location(z=z)
        angle = math.radians(t.rotation.yaw)
        end = begin + carla.Location(x=math.cos(angle), y=math.sin(angle))
        world.debug.draw_arrow(begin, end, arrow_size=0.3, life_time=1.0) 
Example 62
Project: geophys_utils   Author: GeoscienceAustralia   File: _vincenty.py    Apache License 2.0 5 votes vote down vote up
def __init__(self,rmajor,rminor,lon1,lat1,lon2,lat2):
        """
        Define a great circle by specifying:
        rmajor - radius of major axis of ellipsoid
        rminor - radius of minor axis of ellipsoid.
        lon1 - starting longitude of great circle
        lat1 - starting latitude
        lon2 - ending longitude
        lat2 - ending latitude
        All must be given in degrees.

        Instance variables:
        distance - distance along great circle in radians.
        lon1,lat1,lon2,lat2 - start and end points (in radians).
        """
        # convert to radians from degrees.
        lat1 = math.radians(lat1)
        lon1 = math.radians(lon1)
        lat2 = math.radians(lat2)
        lon2 = math.radians(lon2)
        self.a = rmajor
        self.f = (rmajor-rminor)/rmajor
        self.lat1 = lat1
        self.lat2 = lat2
        self.lon1 = lon1
        self.lon2 = lon2
        # distance along geodesic in meters.
        d,a12,a21 = vinc_dist(self.f,  self.a,  lat1,  lon1,  lat2,  lon2 )
        self.distance = d
        self.azimuth12 = a12
        self.azimuth21 = a21
        # great circle arc-length distance (in radians).
        self.gcarclen = 2.*math.asin(math.sqrt((math.sin((lat1-lat2)/2))**2+\
        math.cos(lat1)*math.cos(lat2)*(math.sin((lon1-lon2)/2))**2))
        # check to see if points are antipodal (if so, route is undefined).
        if self.gcarclen == math.pi:
            self.antipodal = True
        else:
            self.antipodal = False 
Example 63
Project: Traffic-Light   Author: team-know-name   File: geomhelper.py    MIT License 5 votes vote down vote up
def fromNaviDegree(degrees):
    return math.pi / 2. - math.radians(degrees) 
Example 64
Project: LaserTOF   Author: kyleuckert   File: test_regression.py    MIT License 5 votes vote down vote up
def test_frompyfunc_endian(self, level=rlevel):
        # Ticket #503
        from math import radians
        uradians = np.frompyfunc(radians, 1, 1)
        big_endian = np.array([83.4, 83.5], dtype='>f8')
        little_endian = np.array([83.4, 83.5], dtype='<f8')
        assert_almost_equal(uradians(big_endian).astype(float),
                            uradians(little_endian).astype(float)) 
Example 65
Project: LaserTOF   Author: kyleuckert   File: backend_agg.py    MIT License 5 votes vote down vote up
def draw_mathtext(self, gc, x, y, s, prop, angle):
        """
        Draw the math text using matplotlib.mathtext
        """
        if __debug__: verbose.report('RendererAgg.draw_mathtext',
                                     'debug-annoying')
        ox, oy, width, height, descent, font_image, used_characters = \
            self.mathtext_parser.parse(s, self.dpi, prop)

        xd = descent * sin(radians(angle))
        yd = descent * cos(radians(angle))
        x = np.round(x + ox + xd)
        y = np.round(y - oy + yd)
        self._renderer.draw_text_image(font_image, x, y + 1, angle, gc) 
Example 66
Project: LaserTOF   Author: kyleuckert   File: backend_agg.py    MIT License 5 votes vote down vote up
def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
        """
        Render the text
        """
        if __debug__: verbose.report('RendererAgg.draw_text', 'debug-annoying')

        if ismath:
            return self.draw_mathtext(gc, x, y, s, prop, angle)

        flags = get_hinting_flag()
        font = self._get_agg_font(prop)

        if font is None: return None
        if len(s) == 1 and ord(s) > 127:
            font.load_char(ord(s), flags=flags)
        else:
            # We pass '0' for angle here, since it will be rotated (in raster
            # space) in the following call to draw_text_image).
            font.set_text(s, 0, flags=flags)
        font.draw_glyphs_to_bitmap(antialiased=rcParams['text.antialiased'])
        d = font.get_descent() / 64.0
        # The descent needs to be adjusted for the angle
        xo, yo = font.get_bitmap_offset()
        xo /= 64.0
        yo /= 64.0
        xd = -d * sin(radians(angle))
        yd = d * cos(radians(angle))

        #print x, y, int(x), int(y), s
        self._renderer.draw_text_image(
            font, np.round(x - xd + xo), np.round(y + yd + yo) + 1, angle, gc) 
Example 67
Project: AboveTustin   Author: kevinabrandon   File: geomath.py    MIT License 4 votes vote down vote up
def bearing(pointA, pointB):
	"""
	Calculates the bearing between two points.

	Found here: https://gist.github.com/jeromer/2005586

	The formulae used is the following:
	    θ = atan2(sin(Δlong).cos(lat2),
	              cos(lat1).sin(lat2) − sin(lat1).cos(lat2).cos(Δlong))

	:Parameters:
	  - `pointA: The tuple representing the latitude/longitude for the
	    first point. Latitude and longitude must be in decimal degrees
	  - `pointB: The tuple representing the latitude/longitude for the
	    second point. Latitude and longitude must be in decimal degrees

	:Returns:
	  The bearing in degrees

	:Returns Type:
	  float
	"""
	if (type(pointA) != tuple) or (type(pointB) != tuple):
		raise TypeError("Only tuples are supported as arguments")

	lat1 = math.radians(pointA[0])
	lat2 = math.radians(pointB[0])

	diffLong = math.radians(pointB[1] - pointA[1])

	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)

	# Now we have the initial bearing but math.atan2 return values
	# from -180° to + 180° which is not what we want for a compass bearing
	# The solution is to normalize the initial bearing as shown below
	initial_bearing = math.degrees(initial_bearing)
	compass_bearing = (initial_bearing + 360) % 360

	return compass_bearing 
Example 68
Project: Physics_Project   Author: QuandisS   File: core_functions.py    Apache License 2.0 4 votes vote down vote up
def return_the_instructions(var):
        if var == 'v0':
            return ['v0x / cos_a', 'v0y / sin_a', '( x - x0 ) / ( cos_a * t ) ', '( L - x0 ) / ( cos_a * t_all )', '( y - y0 + g * t * t / 2 ) / ( sin_a * t )', '( t_all * g ) / ( 2 * sin_a )', 'math.sqrt( ( 2 * g ) / cmath.sin( 2 * alpha ) )', '( vy + g * t ) / sin_a', 'math.sqrt( vy * vy + 2 * g * y ) / sin_a', 'math.sqrt( h_max * 2 * g ) / sin_a']

        if var == 'alpha':
            return ['math.radians( cmath.acos ( cos_a ) )', 'math.radians( cmath.asin ( sin_a ))', 'math.radians( cmath.asin( ( ( L * g ) / ( v0 * v0 )) / 2 )', 'math.radians( math.sqrt( cmath.asin( ( h_max * 2 * g ) / ( v0 * v0 ) ) ))']

        if var == 'g':
            return ['M * G / ( r * r )']

        if var == 'v0x':
            return ['v0 * cos_a', '( x - x0 ) / t', '( L - x0 ) / t_all']

        if var == 'v0y':
            return ['v0 * sin_a', '( y - y0 + g * t * t / 2 ) / t', 't_all * g / 2', 'vy + g * t', 'math.sqrt( vy * vy + 2 * g * y )', 'math.sqrt( h_max * 2 * g )']

        if var == 'vy':
            return ['v0y - g * t', 'v0 * sin_a - g * t', 'math.sqrt( v0y * v0y - 2 * g * y )']

        if var == 't_all':
            return ['( L - x0 ) / ( v0 * cos_a )', '( L - x0 ) / v0x']

        if var == 't':
            return ['( v0y - vy ) / g', '( v0y - v0 * sin_a ) / g', '( x - x0 ) / v0x', '( x - x0 )  / v0 * cos_a']

        if var == 'h_max':
            return ['y0 + v0 * sin_a * 0.5 * t_all - 0.25 * g * t_all * t_all / 2', 'y0 + v0y * 0.5 * t_all - 0.25 * g * t_all * t_all / 2']

        if var == 'x0':
            return ['x - vox * t', 'x - v0 * cos_a * t', 'L - v0 * cos_a * t_all', 'L - v0x * t_all']

        if var == 'x':
            return ['x0 + v0x * t', 'x0 + v0 * cos_a * t']

        if var == 'y0':
            return ['y - v0y * t + g * t * t / 2', 'y - v0 * sin_a * t + g * t * t / 2', 'h_max - v0y * 0.5 * t_all + 0.25 * g * t_all * t_all / 2', 'h_max - v0 * sin_a * 0.5 * t_all + g * t_all * 0.25 * t_all / 2']

        if var == 'y':
            return ['y0 + v0y * t - g * t * t / 2', 'y0 + v0 * sin_a * t - g * t * t / 2', '( vy * vy - v0y * v0y ) / ( -2 * g )', '( vy * vy - v0 * sin_a * v0 * sin_a ) / ( -2 * g )']

        if var == 'L':
            return ['x0 + v0 * cos_a * t_all', 'x0 + v0x * t_all', 'v0 * v0 * math.sin( alpha * 2 ) / g']

        if var == 'F':
            return ['test', 'test']

        if var == 'm':
            return ['test', 'test']

        if var == 'sin_a':
            return ['cmath.sin( alpha )', 'v0y / v0', '( y - y0 + g * t * t / 2 ) / ( v0 * t )', 't_all * g / ( 2 * v0 )', '( t * g + vy ) / v0', 'math.sqrt( h_max * 2 * g ) / v0']

        if var == 'cos_a':
            return ['v0x / v0', '( L - x0 ) / ( v0 * t_all )', '( x - x0 ) / ( v0 * t )', 'cmath.cos( alpha )']


######


# функция берет массив инструкций и словарь переменных
# и ищет инстукцию в которой все переменные известны 
Example 69
Project: directional_drilling_calculations   Author: BrettMontague   File: drillingcalcs.py    MIT License 4 votes vote down vote up
def minimum_curvature_calc(
        distance_between_stations: float,
        azimuth_survey_station_1: float,
        dip_survey_station_1: float,
        azimuth_survey_station_2: float,
        dip_survey_station_2: float,
        convergence: float = 0) -> Tuple[float, float, float, float]:
    ''' 
    Using the length between two surveys, an initial azimuth, an initial dip,
    a secondary azimuth, a secondary dip and an optional grid convergence argument
    , return the tvd difference, northing difference, easting difference and 
    dogleg severity in (°/30m).
    See https://www.onepetro.org/journal-paper/SPE-3362-PA for detail on calculations.
    '''

    # Set variables for the inclination and azimuth of the first two survey points
    inclination_1 = math.radians(dip_survey_station_1)
    azimuth_1 = math.radians(azimuth_survey_station_1 - convergence)

    # Set variables for the inclination and azimuth of the second two survey points
    inclination_2 = math.radians(dip_survey_station_2)
    azimuth_2 = math.radians(azimuth_survey_station_2 - convergence)


    # Calculate the DogLeg
    dogleg = np.arccos(
        np.cos(inclination_2 - inclination_1) - np.sin(inclination_1) *
        np.sin(inclination_2) * (1 - np.cos(azimuth_2 - azimuth_1)))

    # Warn if length is zero, prevent divison by zero.
    if distance_between_stations == 0:
        print('''ERROR: Cannot perform calculation on zero length between 
            survey stations. Return values set to 'None' ''')
        return None, None, None, None

    # Calculate the dogleg severity in (°/30m)
    dogleg_severity = math.degrees(dogleg * (30 / distance_between_stations))

    # Calculate ratio factor.  If there's no dogleg, calculate with balanced tangential instead of minimum curvature.
    if dogleg != 0.0:
        ratio_factor = 2 * np.tan(dogleg / 2) / dogleg  # minimum curvature
    else:
        ratio_factor = 1  # balanced tangential

    # Calculation for TVD depth difference between first and second survey stations
    tvd_difference = (0.5 * distance_between_stations * (
        np.cos(inclination_1) + np.cos(inclination_2)) * ratio_factor)

    # Calculation for northing difference between first and second survey stations
    northing_difference = 0.5 * distance_between_stations * (
        np.sin(inclination_1) * np.cos(azimuth_1) +
        np.sin(inclination_2) * np.cos(azimuth_2)) * ratio_factor

    # Calculation for easting difference between first and second survey stations
    easting_difference = 0.5 * distance_between_stations * (
        np.sin(inclination_1) * np.sin(azimuth_1) +
        np.sin(inclination_2) * np.sin(azimuth_2)) * ratio_factor

    return tvd_difference, northing_difference, easting_difference, dogleg_severity 
Example 70
Project: mpu   Author: MartinThoma   File: __init__.py    MIT License 4 votes vote down vote up
def haversine_distance(origin, destination):
    """
    Calculate the Haversine distance.

    Parameters
    ----------
    origin : tuple of float
        (lat, long)
    destination : tuple of float
        (lat, long)

    Returns
    -------
    distance_in_km : float

    Examples
    --------
    >>> munich = (48.1372, 11.5756)
    >>> berlin = (52.5186, 13.4083)
    >>> round(haversine_distance(munich, berlin), 1)
    504.2

    >>> new_york_city = (40.712777777778, -74.005833333333)  # NYC
    >>> round(haversine_distance(berlin, new_york_city), 1)
    6385.3
    """
    lat1, lon1 = origin
    lat2, lon2 = destination
    if not (-90.0 <= lat1 <= 90):
        raise ValueError("lat1={:2.2f}, but must be in [-90,+90]".format(lat1))
    if not (-90.0 <= lat2 <= 90):
        raise ValueError("lat2={:2.2f}, but must be in [-90,+90]".format(lat2))
    if not (-180.0 <= lon1 <= 180):
        raise ValueError("lon1={:2.2f}, but must be in [-180,+180]"
                         .format(lat1))
    if not (-180.0 <= lon2 <= 180):
        raise ValueError("lon1={:2.2f}, but must be in [-180,+180]"
                         .format(lat1))
    radius = 6371  # km

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

    return d 
Example 71
Project: RLBotPack   Author: RLBot   File: catching.py    MIT License 4 votes vote down vote up
def step(self, dt):

        max_throttle_speed = 1410
        max_boost_speed = 2300

        # get the local coordinates of where the ball is, relative to the car
        # delta_local[0]: how far in front
        # delta_local[1]: how far to the left
        # delta_local[2]: how far above
        delta_local = dot(self.target_pos - self.car.pos, self.car.theta)

        # angle between car's forward direction and target position
        phi = math.atan2(delta_local[1], delta_local[0])

        if phi < -math.radians(10):
            # If the target is more than 10 degrees right from the centre, steer left
            self.controls.steer = -1
        elif phi > math.radians(10):
            # If the target is more than 10 degrees left from the centre, steer right
            self.controls.steer = 1
        else:
            # If the target is less than 10 degrees from the centre, steer straight
            self.controls.steer = phi / math.radians(10)

        if abs(phi) < math.radians(3) and not self.car.supersonic:
            self.controls.boost = True
        else:
            self.controls.boost = False

        if abs(phi) > 1.75:
            self.controls.handbrake = 1
        else:
            self.controls.handbrake = 0

        # forward velocity
        vf = dot(self.car.vel, self.car.forward())

        if vf < self.target_speed:
            self.controls.throttle = 1.0
            if self.target_speed > max_throttle_speed:
                self.controls.boost = 1
            else:
                self.controls.boost = 0
        else:
            self.controls.throttle = -1
            self.controls.boost = 0
            if norm(delta_local) < 20:
                self.controls.throttle = -norm(delta_local) / 20
            if norm(delta_local) < 10:
                self.controls.throttle = -norm(delta_local) / 10

        if self.car.supersonic:
            self.controls.boost = False

        if norm(self.car.pos - self.target_pos) < 100:
            self.finished = True 
Example 72
Project: RLBotPack   Author: RLBot   File: Derevo.py    MIT License 4 votes vote down vote up
def get_controls(self):
        if self.step == "Steer" or self.step == "Dodge2":
            self.step = "Catching"
        if self.step == "Catching":
            target = get_bounce(self)
            if target is None:
                self.step = "Defending"
            else:
                self.catching.target_pos = target[0]
                self.catching.target_speed = (distance_2d(self.info.my_car.pos, target[0]) + 50) / target[1]
                self.catching.step(self.FPS)
                self.controls = self.catching.controls
                ball = self.info.ball
                car = self.info.my_car
                if distance_2d(ball.pos, car.pos) < 150 and 65 < abs(ball.pos[2] - car.pos[2]) < 127:
                    self.step = "Dribbling"
                    self.dribble = Dribbling(self.info.my_car, self.info.ball, self.info.their_goal)
                if self.defending:
                    self.step = "Defending"
                if not self.info.my_car.on_ground:
                    self.step = "Recovery"
                ball = self.info.ball
                if abs(ball.vel[2]) < 100 and sign(self.team) * ball.vel[1] < 0 and sign(self.team) * ball.pos[1] < 0:
                    self.step = "Shooting"
        elif self.step == "Dribbling":
            self.dribble.step(self.FPS)
            self.controls = self.dribble.controls
            ball = self.info.ball
            car = self.info.my_car
            bot_to_opponent = self.info.opponents[0].pos - self.info.my_car.pos
            local_bot_to_target = dot(bot_to_opponent, self.info.my_car.theta)
            angle_front_to_target = math.atan2(local_bot_to_target[1], local_bot_to_target[0])
            opponent_is_near = norm(vec2(bot_to_opponent)) < 2000
            opponent_is_in_the_way = math.radians(-10) < angle_front_to_target < math.radians(10)
            if not (distance_2d(ball.pos, car.pos) < 150 and 65 < abs(ball.pos[2] - car.pos[2]) < 127):
                self.step = "Catching"
            if self.defending:
                self.step = "Defending"
            if opponent_is_near and opponent_is_in_the_way:
                self.step = "Dodge"
                self.dodge = AirDodge(self.info.my_car, 0.25, self.info.their_goal.center)
            if not self.info.my_car.on_ground:
                self.step = "Recovery"
        elif self.step == "Defending":
            defending(self)
        elif self.step == "Dodge":
            self.dodge.step(self.FPS)
            self.controls = self.dodge.controls
            self.controls.boost = 0
            if self.dodge.finished and self.info.my_car.on_ground:
                self.step = "Catching"
        elif self.step == "Recovery":
            self.recovery.step(self.FPS)
            self.controls = self.recovery.controls
            if self.info.my_car.on_ground:
                self.step = "Catching"
        elif self.step == "Shooting":
            shooting(self) 
Example 73
Project: symbolator   Author: kevinpt   File: shapes.py    MIT License 4 votes vote down vote up
def rounded_corner(start, apex, end, rad):

  # Translate all points with apex at origin
  start = (start[0] - apex[0], start[1] - apex[1])
  end = (end[0] - apex[0], end[1] - apex[1])
  
  # Get angles of each line segment
  enter_a = math.atan2(start[1], start[0]) % math.radians(360)
  leave_a = math.atan2(end[1], end[0]) % math.radians(360)
  
  #print('## enter, leave', math.degrees(enter_a), math.degrees(leave_a))
  
  # Determine bisector angle
  ea2 = abs(enter_a - leave_a)
  if ea2 > math.radians(180):
    ea2 = math.radians(360) - ea2
  bisect = ea2 / 2.0
  
  if bisect > math.radians(82): # Nearly colinear: Skip radius
    return (apex, apex, apex, -1)
  
  q = rad * math.sin(math.radians(90) - bisect) / math.sin(bisect)
  
  # Check that q is no more than half the shortest leg
  enter_leg = math.sqrt(start[0]**2 + start[1]**2)
  leave_leg = math.sqrt(end[0]**2 + end[1]**2)
  short_leg = min(enter_leg, leave_leg)
  if q > short_leg / 2:
    q = short_leg / 2
    # Compute new radius
    rad = q * math.sin(bisect) / math.sin(math.radians(90) - bisect)
    
  h = math.sqrt(q**2 + rad**2)
  
  # Center of circle

  # Determine which direction is the smallest angle to the leave point
  # Determine direction of arc
  # Rotate whole system so that enter_a is on x-axis
  delta = (leave_a - enter_a) % math.radians(360)
  if delta < math.radians(180): # CW
    bisect = enter_a + bisect
  else: # CCW
    bisect = enter_a - bisect

  #print('## Bisect2', math.degrees(bisect))
  center = (h * math.cos(bisect) + apex[0], h * math.sin(bisect) + apex[1])
  
  # Find start and end point of arcs
  start_p = (q * math.cos(enter_a) + apex[0], q * math.sin(enter_a) + apex[1])
  end_p = (q * math.cos(leave_a) + apex[0], q * math.sin(leave_a) + apex[1])
  
  return (center, start_p, end_p, rad) 
Example 74
Project: symbolator   Author: kevinpt   File: shapes.py    MIT License 4 votes vote down vote up
def bbox(self):
    lw = self.param('weight')
    if lw is None:
      lw = 0
      
    lw /= 2.0

    # Calculate bounding box for arc segment
    x0, y0, x1, y1 = self.points
    xc = (x0 + x1) / 2.0
    yc = (y0 + y1) / 2.0
    hw = abs(x1 - x0) / 2.0
    hh = abs(y1 - y0) / 2.0

    start = self.options['start'] % 360
    extent = self.options['extent']
    stop = (start + extent) % 360

    if extent < 0:
      start, stop = stop, start  # Swap points so we can rotate CCW

    if stop < start:
      stop += 360 # Make stop greater than start

    angles = [start, stop]

    # Find the extrema of the circle included in the arc
    ortho = (start // 90) * 90 + 90
    while ortho < stop:
      angles.append(ortho)
      ortho += 90 # Rotate CCW


    # Convert all extrema points to cartesian
    points = [(hw * math.cos(math.radians(a)), -hh * math.sin(math.radians(a))) for a in angles]

    points = list(zip(*points))
    x0 = min(points[0]) + xc - lw
    y0 = min(points[1]) + yc - lw
    x1 = max(points[0]) + xc + lw
    y1 = max(points[1]) + yc + lw

    if 'weight' in self.options:
      w = self.options['weight'] / 2.0
      # FIXME: This doesn't properly compensate for the true extrema of the stroked outline
      x0 -= w
      x1 += w
      y0 -= w
      y1 += w

    #print('@@ ARC BB:', (bx0,by0,bx1,by1), hw, hh, angles, start, extent)
    return (x0,y0,x1,y1) 
Example 75
Project: captivox   Author: expectocode   File: captivox.py    GNU General Public License v3.0 4 votes vote down vote up
def paintEvent(self, *_):
        """
        This is called on self.update() and on resize - makes resizes a bit ugly.
        This method draws every frame and forms the core of the program.
        """
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing, True)
        painter.translate(self.width() / 2, self.height() / 2)  # Make (0,0) centre

        if self.draw_axes:
            painter.setPen(QPen(QColor(0, 0, 0, 64), 1))
            # Line(x1,y2,x2,y2)
            painter.drawLine(QLineF(0, self.height() / 2, 0, -self.height() / 2))
            painter.drawLine(QLineF(self.width() / 2, 0, -self.width() / 2, 0))

        colours = interpolate_hsv(self.col1, self.col2, self.num_dots - 2)
        # self.num_dots slider minimum is 2, so middle num minimum 0 which is ok
        last = None

        for cur_dot_num in range(self.num_dots):
            if self.join_end_dots:
                angle_off = radians(self.angle_factor/(self.num_dots-1)) * cur_dot_num
                frame_no = self.frame_no + cur_dot_num*(180/(self.num_dots-1))/self.speedmult
            else:
                angle_off = radians(self.angle_factor/self.num_dots) * cur_dot_num
                frame_no = self.frame_no + cur_dot_num*(180/self.num_dots)/self.speedmult
            # green = (240/self.num_dots) * (self.num_dots - cur_dot_num)
            # blue = (240/self.num_dots) * cur_dot_num
            # colour = QColor(0, green, blue)
            colour = next(colours).toRgb()
            painter.setPen(QPen(colour))
            painter.setBrush(QBrush(colour))
            # progress = (cos(radians(SPEED_MULT * frame_no)) + 1)/2 * 180
            progress = abs((frame_no * self.speedmult) % (2*self.halfmax)-self.halfmax)
            # Progress oscillates every 360/speed_mult frames
            # Progress dictates the range of values of x later fed into cos(x)
            # frame_no multiplier dictates frequency of oscillations
            # Progress ranges between 0 and 180 which later gives us a
            # cos(progress) ranging between # 1 and -1, which combines with
            # sometimes-neg wid * hei to give a full range
            # print(self.frame_no,progress)
            height = sin(angle_off) * (self.height() - 100)
            width = cos(angle_off) * (self.width() - 100)
            # (0,0) is the centre
            x = cos(radians(self.x_multiplier * progress)) * width / 2
            y = cos(radians(self.y_multiplier * progress)) * height / 2

            if self.draw_lines:
                painter.setPen(QPen(colour, self.dot_size))
                painter.drawLine(QPointF(x, y), QPointF(0,0))
                if self.connect_lines:
                    if last:
                        painter.drawLine(QPointF(x, y), last)
                    last = QPointF(x,y)
            else:
                painter.drawEllipse(QPointF(x, y), self.dot_size, self.dot_size) 
Example 76
Project: carla_py   Author: IamWangYunKai   File: global_route_planner.py    MIT License 4 votes vote down vote up
def _turn_decision(self, index, route, threshold=math.radians(5)):
        """
        This method returns the turn decision (RoadOption) for pair of edges
        around current index of route list
        """

        decision = None
        previous_node = route[index-1]
        current_node = route[index]
        next_node = route[index+1]
        next_edge = self._graph.edges[current_node, next_node]
        if index > 0:
            current_edge = self._graph.edges[previous_node, current_node]
            calculate_turn = current_edge['type'].value == RoadOption.LANEFOLLOW.value and \
                not current_edge['intersection'] and \
                    next_edge['type'].value == RoadOption.LANEFOLLOW.value and \
                        next_edge['intersection']
            if calculate_turn:
                cv, nv = current_edge['exit_vector'], next_edge['net_vector']
                cross_list = []
                for neighbor in self._graph.successors(current_node):
                    select_edge = self._graph.edges[current_node, neighbor]
                    if select_edge['type'].value == RoadOption.LANEFOLLOW.value:
                        if neighbor != route[index+1]:
                            sv = select_edge['net_vector']
                            cross_list.append(np.cross(cv, sv)[2])
                next_cross = np.cross(cv, nv)[2]
                deviation = math.acos(np.dot(cv, nv) /\
                    (np.linalg.norm(cv)*np.linalg.norm(nv)))
                if not cross_list:
                    cross_list.append(0)
                if deviation < threshold:
                    decision = RoadOption.STRAIGHT
                elif cross_list and next_cross < min(cross_list):
                    decision = RoadOption.LEFT
                elif cross_list and next_cross > max(cross_list):
                    decision = RoadOption.RIGHT
            else:
                decision = next_edge['type']
        else:
            decision = next_edge['type']

        return decision 
Example 77
Project: carla_py   Author: IamWangYunKai   File: global_route_planner.py    MIT License 4 votes vote down vote up
def _turn_decision(self, index, route, threshold=math.radians(5)):
        """
        This method returns the turn decision (RoadOption) for pair of edges
        around current index of route list
        """

        decision = None
        previous_node = route[index-1]
        current_node = route[index]
        next_node = route[index+1]
        next_edge = self._graph.edges[current_node, next_node]
        if index > 0:
            current_edge = self._graph.edges[previous_node, current_node]
            calculate_turn = current_edge['type'].value == RoadOption.LANEFOLLOW.value and \
                not current_edge['intersection'] and \
                    next_edge['type'].value == RoadOption.LANEFOLLOW.value and \
                        next_edge['intersection']
            if calculate_turn:
                cv, nv = current_edge['exit_vector'], next_edge['net_vector']
                cross_list = []
                for neighbor in self._graph.successors(current_node):
                    select_edge = self._graph.edges[current_node, neighbor]
                    if select_edge['type'].value == RoadOption.LANEFOLLOW.value:
                        if neighbor != route[index+1]:
                            sv = select_edge['net_vector']
                            cross_list.append(np.cross(cv, sv)[2])
                next_cross = np.cross(cv, nv)[2]
                deviation = math.acos(np.dot(cv, nv) /\
                    (np.linalg.norm(cv)*np.linalg.norm(nv)))
                if not cross_list:
                    cross_list.append(0)
                if deviation < threshold:
                    decision = RoadOption.STRAIGHT
                elif cross_list and next_cross < min(cross_list):
                    decision = RoadOption.LEFT
                elif cross_list and next_cross > max(cross_list):
                    decision = RoadOption.RIGHT
            else:
                decision = next_edge['type']
        else:
            decision = next_edge['type']

        return decision 
Example 78
Project: carla_py   Author: IamWangYunKai   File: global_route_planner.py    MIT License 4 votes vote down vote up
def _turn_decision(self, index, route, threshold=math.radians(5)):
        """
        This method returns the turn decision (RoadOption) for pair of edges
        around current index of route list
        """

        decision = None
        previous_node = route[index-1]
        current_node = route[index]
        next_node = route[index+1]
        next_edge = self._graph.edges[current_node, next_node]
        if index > 0:
            current_edge = self._graph.edges[previous_node, current_node]
            calculate_turn = current_edge['type'].value == RoadOption.LANEFOLLOW.value and \
                not current_edge['intersection'] and \
                    next_edge['type'].value == RoadOption.LANEFOLLOW.value and \
                        next_edge['intersection']
            if calculate_turn:
                cv, nv = current_edge['exit_vector'], next_edge['net_vector']
                cross_list = []
                for neighbor in self._graph.successors(current_node):
                    select_edge = self._graph.edges[current_node, neighbor]
                    if select_edge['type'].value == RoadOption.LANEFOLLOW.value:
                        if neighbor != route[index+1]:
                            sv = select_edge['net_vector']
                            cross_list.append(np.cross(cv, sv)[2])
                next_cross = np.cross(cv, nv)[2]
                deviation = math.acos(np.dot(cv, nv) /\
                    (np.linalg.norm(cv)*np.linalg.norm(nv)))
                if not cross_list:
                    cross_list.append(0)
                if deviation < threshold:
                    decision = RoadOption.STRAIGHT
                elif cross_list and next_cross < min(cross_list):
                    decision = RoadOption.LEFT
                elif cross_list and next_cross > max(cross_list):
                    decision = RoadOption.RIGHT
            else:
                decision = next_edge['type']
        else:
            decision = next_edge['type']

        return decision 
Example 79
Project: carla_py   Author: IamWangYunKai   File: global_route_planner.py    MIT License 4 votes vote down vote up
def _turn_decision(self, index, route, threshold=math.radians(5)):
        """
        This method returns the turn decision (RoadOption) for pair of edges
        around current index of route list
        """

        decision = None
        previous_node = route[index-1]
        current_node = route[index]
        next_node = route[index+1]
        next_edge = self._graph.edges[current_node, next_node]
        if index > 0:
            current_edge = self._graph.edges[previous_node, current_node]
            calculate_turn = current_edge['type'].value == RoadOption.LANEFOLLOW.value and \
                not current_edge['intersection'] and \
                    next_edge['type'].value == RoadOption.LANEFOLLOW.value and \
                        next_edge['intersection']
            if calculate_turn:
                cv, nv = current_edge['exit_vector'], next_edge['net_vector']
                cross_list = []
                for neighbor in self._graph.successors(current_node):
                    select_edge = self._graph.edges[current_node, neighbor]
                    if select_edge['type'].value == RoadOption.LANEFOLLOW.value:
                        if neighbor != route[index+1]:
                            sv = select_edge['net_vector']
                            cross_list.append(np.cross(cv, sv)[2])
                next_cross = np.cross(cv, nv)[2]
                deviation = math.acos(np.dot(cv, nv) /\
                    (np.linalg.norm(cv)*np.linalg.norm(nv)))
                if not cross_list:
                    cross_list.append(0)
                if deviation < threshold:
                    decision = RoadOption.STRAIGHT
                elif cross_list and next_cross < min(cross_list):
                    decision = RoadOption.LEFT
                elif cross_list and next_cross > max(cross_list):
                    decision = RoadOption.RIGHT
            else:
                decision = next_edge['type']
        else:
            decision = next_edge['type']

        return decision 
Example 80
Project: honeybee   Author: ladybug-tools   File: room.py    GNU General Public License v3.0 4 votes vote down vote up
def generate_interior_view(self, u=0.5, v=0.5, z=0.5, angle=0,
                               view_up_vector=(0, 0, 1), view_type=0, view_h_size=60,
                               view_v_size=60, x_resolution=64, y_resolution=64,
                               view_shift=0, view_lift=0):
        u"""Generate an inetrior view.

        Args:
            u: u value between 0 and 1.
            v: v value between 0 and 1.
            z: z value between 0 and 1.
            angle: Rotation angle from back wall.
            view_up_vector: Set the view up (-vu) vector (vertical direction) to
                (x, y, z).cDefault: (0, 0, 1)
            view_type: Set view type (-vt) to one of the choices below.
                    0: Perspective (v)
                    1: Hemispherical fisheye (h)
                    2: Parallel (l)
                    3: Cylindrical panorma (c)
                    4: Angular fisheye (a)
                    5: Planisphere [stereographic] projection (s)
                For more detailed description about view types check rpict manual
                page: (http://radsite.lbl.gov/radiance/man_html/rpict.1.html)
            view_h_size: Set the view horizontal size (-vs). For a perspective
                projection (including fisheye views), val is the horizontal field
                of view (in degrees). For a parallel projection, val is the view
                width in world coordinates.
            view_v_size: Set the view vertical size (-vv). For a perspective
                projection (including fisheye views), val is the horizontal field
                of view (in degrees). For a parallel projection, val is the view
                width in world coordinates.
            x_resolution: Set the maximum x resolution (-x) to an integer.
            y_resolution: Set the maximum y resolution (-y) to an integer.
            view_shift: Set the view shift (-vs). This is the amount the actual
                image will be shifted to the right of the specified view. This
                option is useful for generating skewed perspectives or rendering
                an image a piece at a time. A value of 1 means that the rendered
                image starts just to the right of the normal view. A value of −1
                would be to the left. Larger or fractional values are permitted
                as well.
            view_lift: Set the view lift (-vl) to a value. This is the amount the
                actual image will be lifted up from the specified view.
        """
        v = View(self.get_location(u, v, z),
                 self._y_axis.rotate_around(self._z_axis, math.radians(angle)),
                 view_up_vector, view_type, view_h_size, view_v_size,
                 x_resolution, y_resolution, view_shift, view_lift)

        return v