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 File: cairo_backend.py    From symbolator with 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 #2
Source File: room.py    From honeybee with 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 #3
Source File: ball.py    From QPong with 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 #4
Source File: sail_polar_diagram.py    From usv_sim_lsa with 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 #5
Source File: opencv_functional.py    From deep-smoke-machine with 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 #6
Source File: blender_renderer.py    From 3D-R2N2 with 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 #7
Source File: blender_renderer.py    From 3D-R2N2 with 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 #8
Source File: util.py    From BiblioPixel with 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 #9
Source File: geometry.py    From Localization with 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 #10
Source File: functional.py    From opencv_transforms with 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 #11
Source File: shapes.py    From symbolator with MIT License 6 votes vote down vote up
def rotate_bbox(box, a):
  '''Rotate a bounding box 4-tuple by an angle in degrees'''
  corners = ( (box[0], box[1]), (box[0], box[3]), (box[2], box[3]), (box[2], box[1]) )
  a = -math.radians(a)
  sa = math.sin(a)
  ca = math.cos(a)
  
  rot = []
  for p in corners:
    rx = p[0]*ca + p[1]*sa
    ry = -p[0]*sa + p[1]*ca
    rot.append((rx,ry))
  
  # Find the extrema of the rotated points
  rot = list(zip(*rot))
  rx0 = min(rot[0])
  rx1 = max(rot[0])
  ry0 = min(rot[1])
  ry1 = max(rot[1])

  #print('## RBB:', box, rot)
    
  return (rx0, ry0, rx1, ry1) 
Example #12
Source File: geomath.py    From AboveTustin with MIT License 6 votes vote down vote up
def distance(pointA, pointB):
	"""
	Calculate the great circle distance between two points 
	on the earth (specified in decimal degrees)

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

	# haversine formula 
	dlon = lon2 - lon1 
	dlat = lat2 - lat1 
	a = math.sin(dlat/2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon/2)**2
	c = 2 * math.asin(math.sqrt(a)) 
	r = 3956  # Radius of earth in miles. Use 6371 for kilometers
	return c * r 
Example #13
Source File: sphere.py    From sphere with 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 #14
Source File: L.E.S.M.A. - Fabrica de Noobs Speedtest.py    From L.E.S.M.A with 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 #15
Source File: set_attitude_target.py    From dronekit-python with 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 #16
Source File: asthama_search.py    From pepper-robot-programming with 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 #17
Source File: __init__.py    From Traffic-Signs-and-Object-Detection with GNU General Public License v3.0 5 votes vote down vote up
def fetchTiles(latitude, longitude, zoom, maptype, radius_meters=None, default_ntiles=4):
    '''
    Fetches tiles from GoogleMaps at the specified coordinates, zoom level (0-22), and map type ('roadmap', 
    'terrain', 'satellite', or 'hybrid').  The value of radius_meters deteremines the number of tiles that will be 
    fetched; if it is unspecified, the number defaults to default_ntiles.  Tiles are stored as JPEG images 
    in the mapscache folder.
    '''
 
    latitude = _roundto(latitude, _DEGREE_PRECISION)
    longitude = _roundto(longitude, _DEGREE_PRECISION)

    # https://groups.google.com/forum/#!topic/google-maps-js-api-v3/hDRO4oHVSeM
    pixels_per_meter = 2**zoom / (156543.03392 * math.cos(math.radians(latitude)))

    # number of tiles required to go from center latitude to desired radius in meters
    ntiles = default_ntiles if radius_meters is None else int(round(2 * pixels_per_meter / (_TILESIZE /2./ radius_meters))) 

    lonpix = _EARTHPIX + longitude * math.radians(_pixrad)

    sinlat = math.sin(math.radians(latitude))
    latpix = _EARTHPIX - _pixrad * math.log((1 + sinlat)/(1 - sinlat)) / 2

    bigsize = ntiles * _TILESIZE
    bigimage = _new_image(bigsize, bigsize)

    for j in range(ntiles):
        lon = _pix_to_lon(j, lonpix, ntiles, _TILESIZE, zoom)
        for k in range(ntiles):
            lat = _pix_to_lat(k, latpix, ntiles, _TILESIZE, zoom)
            tile = _grab_tile(lat, lon, zoom, maptype, _TILESIZE, 1./_GRABRATE)
            bigimage.paste(tile, (j*_TILESIZE,k*_TILESIZE))

    west = _pix_to_lon(0, lonpix, ntiles, _TILESIZE, zoom)
    east = _pix_to_lon(ntiles-1, lonpix, ntiles, _TILESIZE, zoom)

    north = _pix_to_lat(0, latpix, ntiles, _TILESIZE, zoom)
    south = _pix_to_lat(ntiles-1, latpix, ntiles, _TILESIZE, zoom)

    return bigimage, (north,west), (south,east) 
Example #18
Source File: utils.py    From ingrex_lib with MIT License 5 votes vote down vote up
def calc_dist(lat1, lng1, lat2, lng2):
    lat1, lng1, lat2, lng2 = map(radians, [lat1, lng1, lat2, lng2])
    dlat = lat1 - lat2
    dlng = lng1 - lng2
    a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlng/2)**2
    c = 2* asin(sqrt(a))
    m = 6367.0 * c * 1000
    return m 
Example #19
Source File: metrics.py    From linter-pylama with MIT License 5 votes vote down vote up
def mi_compute(halstead_volume, complexity, sloc, comments):
    '''Compute the Maintainability Index (MI) given the Halstead Volume, the
    Cyclomatic Complexity, the SLOC number and the number of comment lines.
    Usually it is not used directly but instead :func:`~radon.metrics.mi_visit`
    is preferred.
    '''
    if any(metric <= 0 for metric in (halstead_volume, sloc)):
        return 100.
    sloc_scale = math.log(sloc)
    volume_scale = math.log(halstead_volume)
    comments_scale = math.sqrt(2.46 * math.radians(comments))
    # Non-normalized MI
    nn_mi = (171 - 5.2 * volume_scale - .23 * complexity - 16.2 * sloc_scale +
             50 * math.sin(comments_scale))
    return min(max(0., nn_mi * 100 / 171.), 100.) 
Example #20
Source File: parser.py    From tianbot_racecar with GNU General Public License v3.0 5 votes vote down vote up
def convert_knots_to_mps(knots):
    return safe_float(knots) * 0.514444444444


# Need this wrapper because math.radians doesn't auto convert inputs 
Example #21
Source File: worldview.py    From psychsim with MIT License 5 votes vote down vote up
def computeArrow(line):
    point0 = line.p2()
    arrowSize = 25.
    angle = math.atan2(-line.dy(), line.dx())
    point1 = line.p2() - QPointF(math.sin(angle + math.radians(75.)) * arrowSize,
                                          math.cos(angle + math.radians(75.)) * arrowSize)
    point2 = line.p2() - QPointF(math.sin(angle + math.pi - math.radians(75.)) * arrowSize,
                                          math.cos(angle + math.pi - math.radians(75.)) * arrowSize)

    return QPolygonF([point0,point1,point2]) 
Example #22
Source File: parser.py    From tianbot_racecar with GNU General Public License v3.0 5 votes vote down vote up
def convert_deg_to_rads(degs):
    return math.radians(safe_float(degs)) 
Example #23
Source File: GoogleMercatorProjection.py    From PiClock with MIT License 5 votes vote down vote up
def getTileXY(latLng, zoom):
    lat_rad = math.radians(latLng.lat)
    n = 2.0 ** zoom
    xtile = (latLng.lng + 180.0) / 360.0 * n
    ytile = ((1.0 - math.log(math.tan(lat_rad) +
             (1 / math.cos(lat_rad))) / math.pi) / 2.0 * n)
    return {
        'X': xtile,
        'Y': ytile
    } 
Example #24
Source File: sailboat_control_heading.py    From usv_sim_lsa with Apache License 2.0 5 votes vote down vote up
def sail_ctrl():
    global current_heading
    global windDir
    global heeling
    # receber posicaoo do vento (no ref do veleiro)
    x = rospy.get_param('/uwsim/wind/x')
    y = rospy.get_param('/uwsim/wind/y')
    global_dir = math.atan2(y,x)
    heeling = angle_saturation(math.degrees(global_dir)+180)
    #rospy.loginfo("valor de wind_dir = %f", math.degrees(windDir))
    #rospy.loginfo("global_dir = %f", math.degrees(global_dir))
    #rospy.loginfo("current_heading = %f", math.degrees(current_heading))
    wind_dir = global_dir - current_heading
    wind_dir = angle_saturation(math.degrees(wind_dir)+180)
    windDir.data = math.radians(wind_dir)

    #rospy.loginfo("wind_dir = %f", wind_dir)
    #rospy.loginfo("valor de pi/2 = %f", math.pi/2)
    #rospy.loginfo("valor de wind_dir/pi/2 = %f", wind_dir/math.pi/2)
    #rospy.loginfo("valor de sail_max - sail_min = %f", sail_max - sail_min)
    #rospy.loginfo("valor de (sail_max - sail_min) * (wind_dir/(math.pi/2)) = %f", (sail_max - sail_min) * (wind_dir/(math.pi/2)))
    #rospy.loginfo("valor de sail_min = %f", sail_min)
    #sail_angle = sail_min + (sail_max - sail_min) * (wind_dir/180)
    
    sail_angle = math.radians(wind_dir)/2;
    if math.degrees(sail_angle) < -80:
        sail_angle = -sail_angle
    #if sail_angle < 0:
    #    sail_angle = -sail_angle
#    rospy.loginfo("sail angle = %f", math.degrees(sail_angle))
    return -sail_angle 
Example #25
Source File: utils.py    From ingrex_lib with MIT License 5 votes vote down vote up
def calc_tile(lng, lat, zoomlevel):
    tilecounts = [1,1,1,40,40,80,80,320,1E3,2E3,2E3,4E3,8E3,16E3,16E3,32E3]
    rlat = radians(lat)
    tilecount = tilecounts[zoomlevel]
    xtile = int((lng + 180.0) / 360.0 * tilecount)
    ytile = int((1.0 - log(tan(rlat) + (1 / cos(rlat))) / pi) / 2.0 * tilecount)
    return xtile, ytile 
Example #26
Source File: blender_renderer.py    From 3D-R2N2 with MIT License 5 votes vote down vote up
def setViewpoint(self, azimuth, altitude, yaw, distance_ratio, fov):
        self.org_obj.rotation_euler = (0, 0, 0)
        self.light.location = (distance_ratio *
                               (cfg.RENDERING.MAX_CAMERA_DIST + 2), 0, 0)
        self.camera.location = (distance_ratio *
                                cfg.RENDERING.MAX_CAMERA_DIST, 0, 0)
        self.org_obj.rotation_euler = (radians(-yaw),
                                       radians(-altitude),
                                       radians(-azimuth)) 
Example #27
Source File: util.py    From exposure with 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 #28
Source File: util.py    From exposure with 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 #29
Source File: sphere.py    From sphere with MIT License 5 votes vote down vote up
def expand(self, *args):
        if len(args) == 1 and isinstance(args[0], (int, long)):
            level = args[0]
            output = []
            level_lsb = CellId.lsb_for_level(level)
            i = self.num_cells() - 1
            while i >= 0:
                cell_id = self.__cell_ids[i]
                if cell_id.lsb() < level_lsb:
                    cell_id = cell_id.parent(level)
                    while i > 0 and cell_id.contains(self.__cell_ids[i - 1]):
                        i -= 1
                output.append(cell_id)
                cell_id.append_all_neighbors(level, output)
                i -= 1
            self.__cell_ids = output
        elif len(args) == 2 and isinstance(args[0], Angle) \
                and isinstance(args[1], (int, long)):
            min_radius, max_level_diff = args
            min_level = CellId.MAX_LEVEL
            for cell_id in self.__cell_ids:
                min_level = min(min_level, cell_id.level())

            radius_level = CellId.min_width().get_max_level(
                                    min_radius.radians)
            if radius_level == 0 \
                    and min_radius.radians > CellId.min_width().get_value(0):
                self.expand(0)
            self.expand(min(min_level + max_level_diff, radius_level))
        else:
            raise NotImplementedError() 
Example #30
Source File: sphere.py    From sphere with MIT License 5 votes vote down vote up
def expanded(self, margin):
        assert margin.lat().radians > 0
        assert margin.lon().radians > 0
        return self.__class__(
                self.lat().expanded(margin.lat().radians) \
                        .intersection(self.full_lat()),
                self.lon().expanded(margin.lon().radians))