Python math.tan() Examples

The following are code examples for showing how to use math.tan(). 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: PyOptiX   Author: ozen   File: common.py    MIT License 7 votes vote down vote up
def calculate_camera_variables(eye, lookat, up, fov, aspect_ratio, fov_is_vertical=False):
    import numpy as np
    import math

    W = np.array(lookat) - np.array(eye)
    wlen = np.linalg.norm(W)
    U = np.cross(W, np.array(up))
    U /= np.linalg.norm(U)
    V = np.cross(U, W)
    V /= np.linalg.norm(V)

    if fov_is_vertical:
        vlen = wlen * math.tan(0.5 * fov * math.pi / 180.0)
        V *= vlen
        ulen = vlen * aspect_ratio
        U *= ulen
    else:
        ulen = wlen * math.tan(0.5 * fov * math.pi / 180.0)
        U *= ulen
        vlen = ulen * aspect_ratio
        V *= vlen

    return U, V, W 
Example 2
Project: rai-python   Author: MarcToussaint   File: transformations.py    MIT License 6 votes vote down vote up
def shear_matrix(angle, direction, point, normal):
    """Return matrix to shear by angle along direction vector on shear plane.
    The shear plane is defined by a point and normal vector. The direction
    vector must be orthogonal to the plane's normal vector.
    A point P is transformed by the shear matrix into P" such that
    the vector P-P" is parallel to the direction vector and its extent is
    given by the angle of P-P'-P", where P' is the orthogonal projection
    of P onto the shear plane.
    >>> angle = (random.random() - 0.5) * 4*math.pi
    >>> direct = numpy.random.random(3) - 0.5
    >>> point = numpy.random.random(3) - 0.5
    >>> normal = numpy.cross(direct, numpy.random.random(3))
    >>> S = shear_matrix(angle, direct, point, normal)
    >>> numpy.allclose(1.0, numpy.linalg.det(S))
    True
    """
    normal = unit_vector(normal[:3])
    direction = unit_vector(direction[:3])
    if abs(numpy.dot(normal, direction)) > 1e-6:
        raise ValueError("direction and normal vectors are not orthogonal")
    angle = math.tan(angle)
    M = numpy.identity(4)
    M[:3, :3] += angle * numpy.outer(direction, normal)
    M[:3, 3] = -angle * numpy.dot(point[:3], normal) * direction
    return M 
Example 3
Project: sk1-wx   Author: sk1project   File: transforms.py    GNU General Public License v3.0 6 votes vote down vote up
def get_trafo(self):
        angle1 = self.h_shear.get_angle_value()
        angle2 = self.v_shear.get_angle_value()

        m12 = math.tan(angle1)
        m21 = math.tan(angle2)
        m11 = 1.0
        m22 = 1.0 - (m12 * m21)
        trafo = [m11, m21, -m12, m22, 0, 0]

        bbox = self.get_selection_bbox()
        w, h = self.get_selection_size()
        bp = [bbox[0] + w * (1.0 + self.orientation[0]) / 2.0,
              bbox[1] + h * (1.0 + self.orientation[1]) / 2.0]

        new_bp = libgeom.apply_trafo_to_point(bp, trafo)
        trafo[4] = bp[0] - new_bp[0]
        trafo[5] = bp[1] - new_bp[1]
        return trafo 
Example 4
Project: linear_nonlinear_control   Author: Shunichi09   File: main_track.py    MIT License 6 votes vote down vote up
def _func_x_3(self, y_1, y_2, y_3, y_4, u_1, u_2):
        """
        Parameters
        ------------
        y_1 : float
        y_2 : float
        y_3 : float
        u_1 : float
            system input
        u_2 : float
            system input
        """
        # y_dot = u_1 / self.REAR_WHEELE_BASE * math.sin(y_4)
        y_dot = u_1 * math.tan(y_4) / (self.REAR_WHEELE_BASE + self.FRONT_WHEELE_BASE)

        return y_dot 
Example 5
Project: linear_nonlinear_control   Author: Shunichi09   File: main_track.py    MIT License 6 votes vote down vote up
def _func_x_4(self, y_1, y_2, y_3, y_4, u_1, u_2):
        """Ad, Bd, W_D, Q, R
        ParAd, Bd, W_D, Q, R
        ---Ad, Bd, W_D, Q, R
        y_1 : float
        y_2 : float
        y_3 : float
        u_1 : float
            system input
        u_2 : float
            system input
        """
        # y_dot = math.atan2(self.REAR_WHEELE_BASE * math.tan(u_2) ,self.REAR_WHEELE_BASE + self.FRONT_WHEELE_BASE)
        y_dot = - 1. / self.tau * (y_4 - u_2)

        return y_dot 
Example 6
Project: SherpaHighLevel   Author: Shedino   File: mavextra.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def earth_rates(ATTITUDE):
    '''return angular velocities in earth frame'''
    from math import sin, cos, tan, fabs

    p     = ATTITUDE.rollspeed
    q     = ATTITUDE.pitchspeed
    r     = ATTITUDE.yawspeed
    phi   = ATTITUDE.roll
    theta = ATTITUDE.pitch
    psi   = ATTITUDE.yaw

    phiDot   = p + tan(theta)*(q*sin(phi) + r*cos(phi))
    thetaDot = q*cos(phi) - r*sin(phi)
    if fabs(cos(theta)) < 1.0e-20:
        theta += 1.0e-10
    psiDot   = (q*sin(phi) + r*cos(phi))/cos(theta)
    return (phiDot, thetaDot, psiDot) 
Example 7
Project: SherpaHighLevel   Author: Shedino   File: mavextra.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def earth_rates(ATTITUDE):
    '''return angular velocities in earth frame'''
    from math import sin, cos, tan, fabs

    p     = ATTITUDE.rollspeed
    q     = ATTITUDE.pitchspeed
    r     = ATTITUDE.yawspeed
    phi   = ATTITUDE.roll
    theta = ATTITUDE.pitch
    psi   = ATTITUDE.yaw

    phiDot   = p + tan(theta)*(q*sin(phi) + r*cos(phi))
    thetaDot = q*cos(phi) - r*sin(phi)
    if fabs(cos(theta)) < 1.0e-20:
        theta += 1.0e-10
    psiDot   = (q*sin(phi) + r*cos(phi))/cos(theta)
    return (phiDot, thetaDot, psiDot) 
Example 8
Project: PySail-426   Author: j3b4   File: Navigation.py    GNU General Public License v3.0 6 votes vote down vote up
def offset(latA, lonA, Distance, Heading):
    # Takes a position (lat,lon)
    # a distance in nautical miles and a direction in 0-360
    # calculates where you would end up if you started a journey at that
    # heading and moved in a "straight line" (Great Circle)
    # Does not function correctly near the poles
    # I think this is the cosine method
    # haversine would be more accurate
    a = Distance * 1.0 / EARTH_RADIUS
    latB = latA + a * math.cos(Heading)
    if math.copysign(latA-latB, 1) <= math.radians(0.1/3600.0):
        q = math.cos(latA)
    else:
        Df = math.log(math.tan(latB/2+math.pi/4)
                      / math.tan(latA/2+math.pi/4),
                      math.e)
        q = (latB - latA) / Df
    lonB = lonA - a * math.sin(Heading) / q
    return latB, lonB 
Example 9
Project: PySail-426   Author: j3b4   File: Navigation.py    GNU General Public License v3.0 6 votes vote down vote up
def loxodrome(latA, lonA, latB, lonB):  # lossodromica
    # Rhumb line navigation
    # Takes two points on earth and returns:
    # the distance and constant (true) bearing one would need to
    # follow to reach it.
    # Doesn't function near poles:
    # but you shouldn't be sailing near the poles anyways!
    # when latB = -90: math domain error log(0)
    # when latA = -90 [zero divison error]
    # when A==B returns (0.0,0.0)
    # if latA == latB:
    if math.copysign(latA-latB, 1) <= math.radians(0.1/3600.0):
        q = math.cos(latA)
    else:
        Df = math.log(math.tan(latB/2+math.pi/4)
                      / math.tan(latA/2+math.pi/4), math.e)
        q = (latB-latA) * 1.0/Df
    Distance = EARTH_RADIUS * ((latA-latB)**2+(q*(lonA-lonB))**2)**0.5
    Heading = math.atan2(-q*(lonB-lonA), (latB-latA))
    if Heading < 0:
        Heading = Heading + 2.0 * math.pi  # atan2:[-pi,pi]
    return Distance, Heading 
Example 10
Project: pyblish-win   Author: pyblish   File: test_math.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testTan(self):
        self.assertRaises(TypeError, math.tan)
        self.ftest('tan(0)', math.tan(0), 0)
        self.ftest('tan(pi/4)', math.tan(math.pi/4), 1)
        self.ftest('tan(-pi/4)', math.tan(-math.pi/4), -1)
        try:
            self.assertTrue(math.isnan(math.tan(INF)))
            self.assertTrue(math.isnan(math.tan(NINF)))
        except:
            self.assertRaises(ValueError, math.tan, INF)
            self.assertRaises(ValueError, math.tan, NINF)
        self.assertTrue(math.isnan(math.tan(NAN))) 
Example 11
Project: mtrl-auto-uav   Author: brunapearson   File: test_mtrl.py    MIT License 5 votes vote down vote up
def hfov2vfov(hfov, image_sz):
    aspect = image_sz[0]/image_sz[1]
    vfov = 2*math.atan( tan(hfov/2) * aspect)
    return vfov

# compute bounding box size 
Example 12
Project: mtrl-auto-uav   Author: brunapearson   File: test_mtrl.py    MIT License 5 votes vote down vote up
def compute_bb(image_sz, obj_sz, hfov, distance):
    vfov = hfov2vfov(hfov,image_sz)
    box_h = ceil(obj_sz[0] * image_sz[0] / (math.tan(hfov/2)*distance*2))
    box_w = ceil(obj_sz[1] * image_sz[1] / (math.tan(vfov/2)*distance*2))
    return box_h, box_w 
Example 13
Project: streetview_objectmapping   Author: vlkryl   File: objectmapping.py    MIT License 5 votes vote down vote up
def LatLonToMeters( lat, lon ):
    "Converts given lat/lon in WGS84 Datum to XY in Spherical Mercator EPSG:4326"
    originShift = 2 * pi * 6378137 / 2.0
    mx = lon * originShift / 180.0
    my = log( tan((90 + lat) * pi / 360.0 )) / (pi / 180.0)
    my = my * originShift / 180.0
    return mx, my

# conversion from meters to (lat,lon) 
Example 14
Project: nek-type-a   Author: ecopoesis   File: body.py    Apache License 2.0 5 votes vote down vote up
def back_plane_height(x):
    """
    height of the back plane at x
    """
    return (math.tan(math.radians(back_angle())) * x) + min_depth 
Example 15
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 16
Project: Parallel.GAMIT   Author: demiangomez   File: pyVoronoi.py    GNU General Public License v3.0 5 votes vote down vote up
def calculate_surface_area_of_a_spherical_Voronoi_polygon(array_ordered_Voronoi_polygon_vertices,sphere_radius):
    '''Calculate the surface area of a polygon on the surface of a sphere. Based on equation provided here: http://mathworld.wolfram.com/LHuiliersTheorem.html
    Decompose into triangles, calculate excess for each'''
    #have to convert to unit sphere before applying the formula
    spherical_coordinates = convert_cartesian_array_to_spherical_array(array_ordered_Voronoi_polygon_vertices)
    spherical_coordinates[...,0] = 1.0
    array_ordered_Voronoi_polygon_vertices = convert_spherical_array_to_cartesian_array(spherical_coordinates)
    #handle nearly-degenerate vertices on the unit sphere by returning an area close to 0 -- may be better options, but this is my current solution to prevent crashes, etc.
    #seems to be relatively rare in my own work, but sufficiently common to cause crashes when iterating over large amounts of messy data
    if scipy.spatial.distance.pdist(array_ordered_Voronoi_polygon_vertices).min() < (10 ** -7):
        return 10 ** -8
    else:
        n = array_ordered_Voronoi_polygon_vertices.shape[0]
        #point we start from
        root_point = array_ordered_Voronoi_polygon_vertices[0]
        totalexcess = 0
        #loop from 1 to n-2, with point 2 to n-1 as other vertex of triangle
        # this could definitely be written more nicely
        b_point = array_ordered_Voronoi_polygon_vertices[1]
        root_b_dist = calculate_haversine_distance_between_spherical_points(root_point, b_point, 1.0)
        for i in 1 + numpy.arange(n - 2):
            a_point = b_point
            b_point = array_ordered_Voronoi_polygon_vertices[i+1]
            root_a_dist = root_b_dist
            root_b_dist = calculate_haversine_distance_between_spherical_points(root_point, b_point, 1.0)
            a_b_dist = calculate_haversine_distance_between_spherical_points(a_point, b_point, 1.0)
            s = (root_a_dist + root_b_dist + a_b_dist) / 2
            totalexcess += 4 * math.atan(math.sqrt( math.tan(0.5 * s) * math.tan(0.5 * (s-root_a_dist)) * math.tan(0.5 * (s-root_b_dist)) * math.tan(0.5 * (s-a_b_dist))))
        return totalexcess * (sphere_radius ** 2) 
Example 17
Project: pyshgp   Author: erp12   File: numeric.py    MIT License 5 votes vote down vote up
def _tan(x):
    return math.tan(x), 
Example 18
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 19
Project: suncalcPy   Author: Broham   File: suncalc.py    MIT License 5 votes vote down vote up
def rightAscension(l, b): 
	return atan(sin(l) * cos(e) - tan(b) * sin(e), cos(l)) 
Example 20
Project: suncalcPy   Author: Broham   File: suncalc.py    MIT License 5 votes vote down vote up
def azimuth(H, phi, dec):  
	return atan(sin(H), cos(H) * sin(phi) - tan(dec) * cos(phi)) 
Example 21
Project: suncalcPy   Author: Broham   File: suncalc.py    MIT License 5 votes vote down vote up
def getMoonPosition(date, lat, lng):
    lw  = rad * -lng
    phi = rad * lat
    d   = toDays(date)

    c = moonCoords(d)
    H = siderealTime(d, lw) - c["ra"]
    h = altitude(H, phi, c["dec"])

    # altitude correction for refraction
    h = h + rad * 0.017 / tan(h + rad * 10.26 / (h + rad * 5.10))

    return dict(azimuth=azimuth(H, phi, c["dec"]),altitude=h,distance=c["dist"]) 
Example 22
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 23
Project: honeybee   Author: ladybug-tools   File: euclid.py    GNU General Public License v3.0 5 votes vote down vote up
def new_perspective(cls, fov_y, aspect, near, far):
        # from the gluPerspective man page
        f = 1 / math.tan(fov_y / 2)
        self = cls()
        assert near != 0.0 and near != far
        self.a = f / aspect
        self.f = f
        self.k = (far + near) / (near - far)
        self.l = 2 * far * near / (near - far)
        self.o = -1
        self.p = 0
        return self 
Example 24
Project: honeybee   Author: ladybug-tools   File: view.py    GNU General Public License v3.0 5 votes vote down vote up
def get_view_dimension(self, max_x=None, max_y=None):
        """Get dimensions for this view as x, y.

        This method is same as vwrays -d
        """
        max_x = max_x or self.x_resolution
        max_y = max_y or self.y_resolution

        if self.view_type in (1, 4, 5):
            return min(max_x, max_y), min(max_x, max_y)

        vh = self.view_h_size
        vv = self.view_v_size

        if self.view_type == 0:
            hv_ratio = math.tan(math.radians(vh) / 2.0) / \
                math.tan(math.radians(vv) / 2.0)
        else:
            hv_ratio = vh / vv

        # radiance keeps the larges max size and tries to scale the other size
        # to fit the aspect ratio. In case the size doesn't match it reverses
        # the process.
        if max_y <= max_x:
            newx = int(round(hv_ratio * max_y))
            if newx <= max_x:
                return newx, max_y
            else:
                newy = int(round(max_x / hv_ratio))
                return max_x, newy
        else:
            newy = int(round(max_x / hv_ratio))
            if newy <= max_y:
                return max_x, newy
            else:
                newx = int(round(hv_ratio * max_y))
                return newx, max_y 
Example 25
Project: esys-pbi   Author: fsxfreak   File: transformations.py    MIT License 5 votes vote down vote up
def shear_matrix(angle, direction, point, normal):
    """Return matrix to shear by angle along direction vector on shear plane.

    The shear plane is defined by a point and normal vector. The direction
    vector must be orthogonal to the plane's normal vector.

    A point P is transformed by the shear matrix into P" such that
    the vector P-P" is parallel to the direction vector and its extent is
    given by the angle of P-P'-P", where P' is the orthogonal projection
    of P onto the shear plane.

    >>> angle = (random.random() - 0.5) * 4*math.pi
    >>> direct = numpy.random.random(3) - 0.5
    >>> point = numpy.random.random(3) - 0.5
    >>> normal = numpy.cross(direct, numpy.random.random(3))
    >>> S = shear_matrix(angle, direct, point, normal)
    >>> numpy.allclose(1, numpy.linalg.det(S))
    True

    """
    normal = unit_vector(normal[:3])
    direction = unit_vector(direction[:3])
    if abs(numpy.dot(normal, direction)) > 1e-6:
        raise ValueError("direction and normal vectors are not orthogonal")
    angle = math.tan(angle)
    M = numpy.identity(4)
    M[:3, :3] += angle * numpy.outer(direction, normal)
    M[:3, 3] = -angle * numpy.dot(point[:3], normal) * direction
    return M 
Example 26
Project: sk1-wx   Author: sk1project   File: patternctrls.py    GNU General Public License v3.0 5 votes vote down vote up
def get_trafo(self):
        x0 = self.origin_x.get_point_value()
        y0 = self.origin_y.get_point_value()
        sx = self.scale_x.get_value() / 100.0
        sy = self.scale_y.get_value() / 100.0
        shx = self.shear_x.get_value()
        shy = self.shear_y.get_value()

        if shx + shy > 85:
            if shx == self.transforms[3]:
                shy = 85 - shx
            else:
                shx = 85 - shy

        shx = math.pi * shx / 180.0
        shy = math.pi * shy / 180.0

        angle = math.pi * self.rotate.get_value() / 180.0

        trafo = [sx, 0.0, 0.0, sy, x0, y0]
        if angle:
            trafo2 = [math.cos(angle), math.sin(angle),
                      - math.sin(angle), math.cos(angle), 0.0, 0.0]
            trafo = libgeom.multiply_trafo(trafo, trafo2)
        if shx or shy:
            trafo2 = [1.0, math.tan(shy), math.tan(shx), 1.0, 0.0, 0.0]
            trafo = libgeom.multiply_trafo(trafo, trafo2)

        self.transforms = [sx, sy, shx, shy, angle]
        return trafo, [sx, sy, shx, shy, angle] 
Example 27
Project: AutoRun-Car   Author: valext   File: rc_driver.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def calculate(self, v, h, x_shift, image):
        # compute and return the distance from the target point to the camera
        d = h / math.tan(self.alpha + math.atan((v - self.v0) / self.ay))
        if d > 0:
            cv2.putText(image, "%.1fcm" % d,
                (image.shape[1] - x_shift, image.shape[0] - 20), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2)
        return d 
Example 28
Project: LaserTOF   Author: kyleuckert   File: test_quadpack.py    MIT License 5 votes vote down vote up
def setUp(self):
        if sys.platform == 'win32':
            if sys.version_info < (3, 5):
                files = [ctypes.util.find_msvcrt()]
            else:
                files = ['api-ms-win-crt-math-l1-1-0.dll']
        elif sys.platform == 'darwin':
            files = ['libm.dylib']
        else:
            files = ['libm.so', 'libm.so.6']

        for file in files:
            try:
                self.lib = ctypes.CDLL(file)
                break
            except OSError:
                pass
        else:
            # This test doesn't work on some Linux platforms (Fedora for
            # example) that put an ld script in libm.so - see gh-5370
            self.skipTest("Ctypes can't import libm.so")

        restype = ctypes.c_double
        argtypes = (ctypes.c_double,)
        for name in ['sin', 'cos', 'tan']:
            func = getattr(self.lib, name)
            func.restype = restype
            func.argtypes = argtypes 
Example 29
Project: LaserTOF   Author: kyleuckert   File: test_quadpack.py    MIT License 5 votes vote down vote up
def test_typical(self):
        assert_quad(quad(self.lib.sin, 0, 5), quad(math.sin, 0, 5)[0])
        assert_quad(quad(self.lib.cos, 0, 5), quad(math.cos, 0, 5)[0])
        assert_quad(quad(self.lib.tan, 0, 1), quad(math.tan, 0, 1)[0]) 
Example 30
Project: icarus   Author: tripzero   File: tracker_funcs.py    GNU General Public License v3.0 5 votes vote down vote up
def calcTiltHeight(self, o_a_dist1, input_time):
		val = 69 - self.alt(self.lat, self.lon, input_time)
		left = tan(radians(val))
		right = o_a_dist1
		x = left * right
		#print ("Effective actuator1 height: ", '{:.5f}'.format(x), " inches")
		return x 
Example 31
Project: NiujiaoDebugger   Author: MrSrc   File: test_math.py    GNU General Public License v3.0 5 votes vote down vote up
def testTan(self):
        self.assertRaises(TypeError, math.tan)
        self.ftest('tan(0)', math.tan(0), 0)
        self.ftest('tan(pi/4)', math.tan(math.pi/4), 1)
        self.ftest('tan(-pi/4)', math.tan(-math.pi/4), -1)
        try:
            self.assertTrue(math.isnan(math.tan(INF)))
            self.assertTrue(math.isnan(math.tan(NINF)))
        except:
            self.assertRaises(ValueError, math.tan, INF)
            self.assertRaises(ValueError, math.tan, NINF)
        self.assertTrue(math.isnan(math.tan(NAN))) 
Example 32
Project: myfenjalinuxcnc   Author: GuiHue   File: probe_screen.py    GNU General Public License v3.0 5 votes vote down vote up
def calc_cross_rott(self,x1=0.,y1=0.,x2=0.,y2=0.,a1=0.,a2=90.) :
        coord = [0,0]
        k1=math.tan(math.radians(a1))
        k2=math.tan(math.radians(a2))
        coord[0]=(k1*x1-k2*x2+y2-y1)/(k1-k2)
        coord[1]=k1*(coord[0]-x1)+y1
        return coord

    # rotate point coordinates 
Example 33
Project: laplacian-meshes   Author: bmershon   File: LapGUI.py    GNU General Public License v3.0 5 votes vote down vote up
def MouseMotion(self, evt):
        state = wx.GetMouseState()
        x, y = evt.GetPosition()
        [lastX, lastY] = self.MousePos
        self.handleMouseStuff(x, y)
        dX = self.MousePos[0] - lastX
        dY = self.MousePos[1] - lastY
        if evt.Dragging():
            idx = self.laplaceCurrentIdx
            if self.GUIState == STATE_CHOOSELAPLACEVERTICES and (state.CmdDown() or self.pressingC) and self.laplaceCurrentIdx in self.laplacianConstraints:
                #Move up laplacian mesh constraint based on where the user drags
                #the mouse
                t = self.camera.towards
                u = self.camera.up
                r = np.cross(t, u)
                P0 = self.laplacianConstraints[idx]
                #Construct a plane going through the point which is parallel to the
                #viewing plane
                plane = Plane3D(P0, t)
                #Construct a ray through the pixel where the user is clicking
                tanFOV = math.tan(self.camera.yfov/2)
                scaleX = tanFOV*(self.MousePos[0] - self.size.x/2)/(self.size.x/2)
                scaleY = tanFOV*(self.MousePos[1] - self.size.y/2)/(self.size.y/2)
                V = t + scaleX*r + scaleY*u
                ray = Ray3D(self.camera.eye, V)
                self.laplacianConstraints[idx] = ray.intersectPlane(plane)[1]
            else:
                #Translate/rotate shape
                if evt.MiddleIsDown():
                    self.camera.translate(dX, dY)
                elif evt.RightIsDown():
                    self.camera.zoom(-dY)#Want to zoom in as the mouse goes up
                elif evt.LeftIsDown():
                    self.camera.orbitLeftRight(dX)
                    self.camera.orbitUpDown(dY)
        self.Refresh() 
Example 34
Project: laplacian-meshes   Author: bmershon   File: meshView.py    GNU General Public License v3.0 5 votes vote down vote up
def MouseMotion(self, evt):
        state = wx.GetMouseState()
        x, y = evt.GetPosition()
        [lastX, lastY] = self.MousePos
        self.handleMouseStuff(x, y)
        dX = self.MousePos[0] - lastX
        dY = self.MousePos[1] - lastY
        if evt.Dragging():
            idx = self.laplaceCurrentIdx
            if self.GUIState == STATE_CHOOSELAPLACEVERTICES and state.ControlDown() and self.laplaceCurrentIdx in self.laplacianConstraints:
                #Move up laplacian mesh constraint based on where the user drags
                #the mouse
                t = self.camera.towards
                u = self.camera.up
                r = np.cross(t, u)
                P0 = self.laplacianConstraints[idx]
                #Construct a plane going through the point which is parallel to the
                #viewing plane
                plane = Plane3D(P0, t)
                #Construct a ray through the pixel where the user is clicking
                tanFOV = math.tan(self.camera.yfov/2)
                scaleX = tanFOV*(self.MousePos[0] - self.size.x/2)/(self.size.x/2)
                scaleY = tanFOV*(self.MousePos[1] - self.size.y/2)/(self.size.y/2)
                V = t + scaleX*r + scaleY*u
                ray = Ray3D(self.camera.eye, V)
                self.laplacianConstraints[idx] = ray.intersectPlane(plane)[1]
            else:
                #Translate/rotate shape
                if evt.MiddleIsDown():
                    self.camera.translate(dX, dY)
                elif evt.RightIsDown():
                    self.camera.zoom(-dY)#Want to zoom in as the mouse goes up
                elif evt.LeftIsDown():
                    self.camera.orbitLeftRight(dX)
                    self.camera.orbitUpDown(dY)
        self.Refresh() 
Example 35
Project: laplacian-meshes   Author: bmershon   File: Cameras3D.py    GNU General Public License v3.0 5 votes vote down vote up
def getPerspectiveMatrix(yfov, aspect, near, far):
    f = 1.0/math.tan(yfov/2)
    nf = 1/(near - far)
    mat = np.zeros(16)
    mat[0] = f/aspect
    mat[5] = f
    mat[10] = (far + near)*nf
    mat[11] = -1
    mat[14] = (2*far*near)*nf
    return mat 
Example 36
Project: laplacian-meshes   Author: bmershon   File: Cameras3D.py    GNU General Public License v3.0 5 votes vote down vote up
def translate(self, dx, dy):
        length = self.center - self.eye
        length = np.sqrt(np.sum(length**2))*math.tan(self.yfov)
        dx = length*dx / float(self.pixWidth)
        dy = length*dy / float(self.pixHeight)
        r = np.cross(self.towards, self.up)
        self.center = self.center - dx*r - dy*self.up
        self.eye = self.eye - dx*r - dy*self.up
        self.updateVecsFromPolar() 
Example 37
Project: vo_single_camera_sos   Author: ubuntuslave   File: euclid.py    GNU General Public License v3.0 5 votes vote down vote up
def new_perspective(cls, fov_y, aspect, near, far):
        # from the gluPerspective man page
        f = 1 / math.tan(fov_y / 2)
        self = cls()
        assert near != 0.0 and near != far
        self.a = f / aspect
        self.f = f
        self.k = (far + near) / (near - far)
        self.l = 2 * far * near / (near - far)
        self.o = -1
        self.p = 0
        return self 
Example 38
Project: vo_single_camera_sos   Author: ubuntuslave   File: transformations.py    GNU General Public License v3.0 5 votes vote down vote up
def shear_matrix(angle, direction, point, normal):
    """Return matrix to shear by angle along direction vector on shear plane.

    The shear plane is defined by a point and normal vector. The direction
    vector must be orthogonal to the plane's normal vector.

    A point P is transformed by the shear matrix into P" such that
    the vector P-P" is parallel to the direction vector and its extent is
    given by the angle of P-P'-P", where P' is the orthogonal projection
    of P onto the shear plane.

    >>> angle = (random.random() - 0.5) * 4*math.pi
    >>> direct = numpy.random.random(3) - 0.5
    >>> point = numpy.random.random(3) - 0.5
    >>> normal = numpy.cross(direct, numpy.random.random(3))
    >>> S = shear_matrix(angle, direct, point, normal)
    >>> numpy.allclose(1, numpy.linalg.det(S))
    True

    """
    normal = unit_vector(normal[:3])
    direction = unit_vector(direction[:3])
    if abs(numpy.dot(normal, direction)) > 1e-6:
        raise ValueError("direction and normal vectors are not orthogonal")
    angle = math.tan(angle)
    M = numpy.identity(4)
    M[:3, :3] += angle * numpy.outer(direction, normal)
    M[:3, 3] = -angle * numpy.dot(point[:3], normal) * direction
    return M 
Example 39
Project: Bilibili-   Author: ytx1991   File: GetAssDanmaku.py    MIT License 5 votes vote down vote up
def get(self, index, default=None):
        try:
            return self[index]
        except IndexError:
            return default

# Calculation is based on https://github.com/jabbany/CommentCoreLibrary/issues/5#issuecomment-40087282
#                     and https://github.com/m13253/danmaku2ass/issues/7#issuecomment-41489422
# ASS FOV = width*4/3.0
# But Flash FOV = width/math.tan(100*math.pi/360.0)/2 will be used instead
# Result: (transX, transY, rotX, rotY, rotZ, scaleX, scaleY) 
Example 40
Project: Bilibili-   Author: ytx1991   File: GetAssDanmaku.py    MIT License 5 votes vote down vote up
def ConvertFlashRotation(rotY, rotZ, X, Y, width, height):
    def WrapAngle(deg):
        return 180-((180-deg) % 360)
    rotY = WrapAngle(rotY)
    rotZ = WrapAngle(rotZ)
    if rotY in (90, -90):
        rotY -= 1
    if rotY == 0 or rotZ == 0:
        outX = 0
        outY = -rotY  # Positive value means clockwise in Flash
        outZ = -rotZ
        rotY *= math.pi/180.0
        rotZ *= math.pi/180.0
    else:
        rotY *= math.pi/180.0
        rotZ *= math.pi/180.0
        outY = math.atan2(-math.sin(rotY)*math.cos(rotZ), math.cos(rotY))*180/math.pi
        outZ = math.atan2(-math.cos(rotY)*math.sin(rotZ), math.cos(rotZ))*180/math.pi
        outX = math.asin(math.sin(rotY)*math.sin(rotZ))*180/math.pi
    trX = (X*math.cos(rotZ)+Y*math.sin(rotZ))/math.cos(rotY)+(1-math.cos(rotZ)/math.cos(rotY))*width/2-math.sin(rotZ)/math.cos(rotY)*height/2
    trY = Y*math.cos(rotZ)-X*math.sin(rotZ)+math.sin(rotZ)*width/2+(1-math.cos(rotZ))*height/2
    trZ = (trX-width/2)*math.sin(rotY)
    FOV = width*math.tan(2*math.pi/9.0)/2
    try:
        scaleXY = FOV/(FOV+trZ)
    except ZeroDivisionError:
        logging.error('Rotation makes object behind the camera: trZ == %.0f' % trZ)
        scaleXY = 1
    trX = (trX-width/2)*scaleXY+width/2
    trY = (trY-height/2)*scaleXY+height/2
    if scaleXY < 0:
        scaleXY = -scaleXY
        outX += 180
        outY += 180
        logging.error('Rotation makes object behind the camera: trZ == %.0f < %.0f' % (trZ, FOV))
    return (trX, trY, WrapAngle(outX), WrapAngle(outY), WrapAngle(outZ), scaleXY*100, scaleXY*100) 
Example 41
Project: tributary   Author: timkpaine   File: ops.py    Apache License 2.0 5 votes vote down vote up
def Tan(self):
    return self._gennode('tan(' + self._name + ')', (lambda x: math.tan(self.value())), [self], self._trace) 
Example 42
Project: tributary   Author: timkpaine   File: ops.py    Apache License 2.0 5 votes vote down vote up
def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
    if ufunc == np.add:
        if isinstance(inputs[0], _Node):
            return inputs[0].__add__(inputs[1])
        else:
            return inputs[1].__add__(inputs[0])
    elif ufunc == np.subtract:
        if isinstance(inputs[0], _Node):
            return inputs[0].__sub__(inputs[1])
        else:
            return inputs[1].__sub__(inputs[0])
    elif ufunc == np.multiply:
        if isinstance(inputs[0], _Node):
            return inputs[0].__mul__(inputs[1])
        else:
            return inputs[1].__mul__(inputs[0])
    elif ufunc == np.divide:
        if isinstance(inputs[0], _Node):
            return inputs[0].__truedivide__(inputs[1])
        else:
            return inputs[1].__truedivide__(inputs[0])
    elif ufunc == np.sin:
        return inputs[0].sin()
    elif ufunc == np.cos:
        return inputs[0].cos()
    elif ufunc == np.tan:
        return inputs[0].tan()
    elif ufunc == np.arcsin:
        return inputs[0].arcsin()
    elif ufunc == np.arccos:
        return inputs[0].arccos()
    elif ufunc == np.arctan:
        return inputs[0].arctan()
    elif ufunc == np.exp:
        return inputs[0].exp()
    elif ufunc == sp.special.erf:
        return inputs[0].erf()
    else:
        raise NotImplementedError('Not Implemented!') 
Example 43
Project: tributary   Author: timkpaine   File: ops.py    Apache License 2.0 5 votes vote down vote up
def Tan(foo, foo_kwargs=None):
    return unary(lambda x: math.tan(x), foo, foo_kwargs, _name='Tan')


# Arithmetic 
Example 44
Project: 2018-1-OSS-E7   Author: 18-1-SKKU-OSS   File: imageToGcode.py    MIT License 5 votes vote down vote up
def vee_common(angle, rough_offset=0.0):
	slope = math.tan(math.pi/2.0 - (angle / 2.0) * math.pi / 180.0)
	def f(r, dia):
		return r * slope
	return f 
Example 45
Project: self_driving_car   Author: theroyakash   File: manual_control_steeringwheel.py    GNU General Public License v3.0 5 votes vote down vote up
def _parse_vehicle_wheel(self):
        numAxes = self._joystick.get_numaxes()
        jsInputs = [float(self._joystick.get_axis(i)) for i in range(numAxes)]
        # print (jsInputs)
        jsButtons = [float(self._joystick.get_button(i)) for i in
                     range(self._joystick.get_numbuttons())]

        # Custom function to map range of inputs [1, -1] to outputs [0, 1] i.e 1 from inputs means nothing is pressed
        # For the steering, it seems fine as it is
        K1 = 1.0  # 0.55
        steerCmd = K1 * math.tan(1.1 * jsInputs[self._steer_idx])

        K2 = 1.6  # 1.6
        throttleCmd = K2 + (2.05 * math.log10(
            -0.7 * jsInputs[self._throttle_idx] + 1.4) - 1.2) / 0.92
        if throttleCmd <= 0:
            throttleCmd = 0
        elif throttleCmd > 1:
            throttleCmd = 1

        brakeCmd = 1.6 + (2.05 * math.log10(
            -0.7 * jsInputs[self._brake_idx] + 1.4) - 1.2) / 0.92
        if brakeCmd <= 0:
            brakeCmd = 0
        elif brakeCmd > 1:
            brakeCmd = 1

        self._control.steer = steerCmd
        self._control.brake = brakeCmd
        self._control.throttle = throttleCmd

        #toggle = jsButtons[self._reverse_idx]

        self._control.hand_brake = bool(jsButtons[self._handbrake_idx]) 
Example 46
Project: PyR2   Author: caelan   File: genericRobot.py    MIT License 5 votes vote down vote up
def mapToTan(t, limits):
    (tlo, thi) = limits
    mapped = ((2*t - thi - tlo)/(thi-tlo))
    assert -1 <= mapped <= 1
    return math.tan((math.pi/2) * mapped) 
Example 47
Project: PyR2   Author: caelan   File: transformations.py    MIT License 5 votes vote down vote up
def shear_matrix(angle, direction, point, normal):
    """Return matrix to shear by angle along direction vector on shear plane.

    The shear plane is defined by a point and normal vector. The direction
    vector must be orthogonal to the plane's normal vector.

    A point P is transformed by the shear matrix into P" such that
    the vector P-P" is parallel to the direction vector and its extent is
    given by the angle of P-P'-P", where P' is the orthogonal projection
    of P onto the shear plane.

    >>> angle = (random.random() - 0.5) * 4*math.pi
    >>> direct = numpy.random.random(3) - 0.5
    >>> point = numpy.random.random(3) - 0.5
    >>> normal = numpy.cross(direct, numpy.random.random(3))
    >>> S = shear_matrix(angle, direct, point, normal)
    >>> numpy.allclose(1.0, numpy.linalg.det(S))
    True

    """
    normal = unit_vector(normal[:3])
    direction = unit_vector(direction[:3])
    if abs(numpy.dot(normal, direction)) > 1e-6:
        raise ValueError("direction and normal vectors are not orthogonal")
    angle = math.tan(angle)
    M = numpy.identity(4)
    M[:3, :3] += angle * numpy.outer(direction, normal)
    M[:3, 3] = -angle * numpy.dot(point[:3], normal) * direction
    return M 
Example 48
Project: linear_nonlinear_control   Author: Shunichi09   File: main_track.py    MIT License 5 votes vote down vote up
def calc_predict_sytem_model(self, V, curvatures, predict_step):
        """
        calc next predict systemo models
        V : float
            current speed of car
        curvatures : list
            this is the next curvature's list
        predict_step : int
            predict step of MPC
        """
        for i in range(predict_step):
            delta_r = math.atan2(self.WHEEL_BASE, 1. / curvatures[i])

            A12 = (V / self.WHEEL_BASE) / (math.cos(delta_r)**2)
            A22 = (1. - 1. / self.tau * self.dt)

            Ad = np.array([[1., V * self.dt,   0.], 
                           [0., 1., A12 * self.dt],
                           [0., 0., A22]])

            Bd = np.array([[0.], [0.], [1. / self.tau]]) * self.dt

            # -v*curvature + v/L*(tan(delta_r)-delta_r*cos_delta_r_squared_inv);
            # W_D_0 = V / self.WHEEL_BASE * (delta_r / (math.cos(delta_r)**2)
            W_D_0 = -V * curvatures[i] + (V / self.WHEEL_BASE) * (math.tan(delta_r) - delta_r / (math.cos(delta_r)**2))

            W_D = np.array([[0.], [W_D_0], [0.]]) * self.dt

            self.Ad_s.append(Ad)
            self.Bd_s.append(Bd)
            self.W_D_s.append(W_D)

        # return self.Ad_s, self.Bd_s, self.W_D_s 
Example 49
Project: complex_behaviors   Author: cpswarm   File: bag.py    Apache License 2.0 5 votes vote down vote up
def process(self, fov, verbose=False):
        '''
        process bag file contents to get data
        :param float fov: field of view of the UAVs in radian
        :param bool verbose: whether to be verbose (default False)
        '''
        # compute altitude
        alt = 0
        if len(self.pose) > 0:
            alts = [p[3] for p in self.pose]
            alt = sum(alts) / len(alts)

        # area visible to UAVs in each direction (inflation of line)
        self.fov = alt * math.tan(fov/2)

        if verbose:
            print("Tracking camera field of view:\n  fov = {0:.2f} m * tan({1:.2f}/2) = {2:.2f} m".format(alt, fov, self.fov))

        # create a line string that represents the trajectory of the UAV
        if len(self.pose) > 0:
            self.traj = geo.LineString(self.path(self.tstop))
        else:
            self.traj = geo.LineString()

        if verbose:
            #print("Average velocity:\n  v = {0:.2f}/{1:.2f} = {2:.2f}".format(self.traj.length, self.time[-1]-self.time[0], self.traj.length / (self.time[-1]-self.time[0])))
            if self.tstop != self.tstart:
                print("Average velocity:\n  v = {0:.2f} m / {1:.2f} s = {2:.2f} m/s".format(self.traj.length, self.tstop-self.tstart, self.traj.length / (self.tstop-self.tstart))) 
Example 50
Project: PencilDrawing   Author: CharlesPikachu   File: drawing.py    MIT License 5 votes vote down vote up
def __strokeGeneration(self, img):
		h, w = img.shape
		kernel_size = int(min(w, h) * self.kernel_size_scale)
		kernel_size += kernel_size % 2
		# compute gradients, yielding magnitude
		img_double = im2double(img)
		dx = np.concatenate((np.abs(img_double[:, 0:-1]-img_double[:, 1:]), np.zeros((h, 1))), 1)
		dy = np.concatenate((np.abs(img_double[0:-1, :]-img_double[1:, :]), np.zeros((1, w))), 0)
		img_gradient = np.sqrt(np.power(dx, 2) + np.power(dy, 2))
		# choose eight reference directions
		line_segments = np.zeros((kernel_size, kernel_size, 8))
		for i in [0, 1, 2, 7]:
			for x in range(kernel_size):
				y = round((x + 1 - kernel_size / 2) * math.tan(math.pi / 8 * i))
				y = kernel_size / 2 - y
				if y > 0 and y <= kernel_size:
					line_segments[int(y-1), x, i] = 1
				if i == 7:
					line_segments[:, :, 3] = np.rot90(line_segments[:, :, 7], -1)
				else:
					line_segments[:, :, i+4] = np.rot90(line_segments[:, :, i], 1)
		# get response maps for the reference directions
		response_maps = np.zeros((h, w, 8))
		for i in range(8):
			response_maps[:, :, i] = signal.convolve2d(img_gradient, line_segments[:, :, i], 'same')
		response_maps_maxvalueidx = response_maps.argmax(axis=-1)
		# the classification is performed by selecting the maximum value among the responses in all directions
		magnitude_maps = np.zeros_like(response_maps)
		for i in range(8):
			magnitude_maps[:, :, i] = img_gradient * (response_maps_maxvalueidx == i).astype('float')
		# line shaping
		stroke_maps = np.zeros_like(response_maps)
		for i in range(8):
			stroke_maps[:, :, i] = signal.convolve2d(magnitude_maps[:, :, i], line_segments[:, :, i], 'same')
		stroke_maps = stroke_maps.sum(axis=-1)
		stroke_maps = (stroke_maps - stroke_maps.min()) / (stroke_maps.max() - stroke_maps.min())
		stroke_maps = (1 - stroke_maps) * self.stroke_width
		return stroke_maps 
Example 51
Project: cozmo_driver   Author: OTL   File: transformations.py    Apache License 2.0 5 votes vote down vote up
def shear_matrix(angle, direction, point, normal):
    """Return matrix to shear by angle along direction vector on shear plane.

    The shear plane is defined by a point and normal vector. The direction
    vector must be orthogonal to the plane's normal vector.

    A point P is transformed by the shear matrix into P" such that
    the vector P-P" is parallel to the direction vector and its extent is
    given by the angle of P-P'-P", where P' is the orthogonal projection
    of P onto the shear plane.

    >>> angle = (random.random() - 0.5) * 4*math.pi
    >>> direct = numpy.random.random(3) - 0.5
    >>> point = numpy.random.random(3) - 0.5
    >>> normal = numpy.cross(direct, numpy.random.random(3))
    >>> S = shear_matrix(angle, direct, point, normal)
    >>> numpy.allclose(1.0, numpy.linalg.det(S))
    True

    """
    normal = unit_vector(normal[:3])
    direction = unit_vector(direction[:3])
    if abs(numpy.dot(normal, direction)) > 1e-6:
        raise ValueError("direction and normal vectors are not orthogonal")
    angle = math.tan(angle)
    M = numpy.identity(4)
    M[:3, :3] += angle * numpy.outer(direction, normal)
    M[:3, 3] = -angle * numpy.dot(point[:3], normal) * direction
    return M 
Example 52
Project: four-wheel-steer-teleop   Author: gkouros   File: four_wheel_steer_teleop.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def pub_callback(self, event):
        cmd_msg = Twist()
        cmd_msg.linear.x = self.speed * cos(self.steering_angle * self.mode)
        cmd_msg.linear.y = self.speed * sin(self.steering_angle * self.mode)
        cmd_msg.angular.z = 2 * self.speed \
                * cos(self.steering_angle * self.mode) \
                * tan(self.steering_angle) * (1 - self.mode) / self.wheelbase
        self.drive_pub.publish(cmd_msg) 
Example 53
Project: GlyphsScripts   Author: simoncozens   File: Sansomatic.py    MIT License 5 votes vote down vote up
def drawAngledRectangle(x,y,w,h,angle):
  correctedWidth = stemWidthForTargetWeight(w, angle)
  bottomOffset = tan(angle) * h
  bl = GSNode((x+bottomOffset,y), type = LINE)
  br = GSNode((x+correctedWidth+bottomOffset,y), type = LINE)
  tr = GSNode((x+correctedWidth,y+h), type = LINE)
  tl = GSNode((x,y+h), type = LINE)
  p = GSPath()
  p.nodes = [bl,br,tr,tl]
  p.closed = True
  Glyphs.font.selectedLayers[0].paths.append(p)
  return x+bottomOffset 
Example 54
Project: GlyphsScripts   Author: simoncozens   File: Sansomatic.py    MIT License 5 votes vote down vote up
def A(controls):
  angle = getControl(controls, "Angle")
  stem = getDimension("HV")
  crossbar = getDimension("HH")
  overlap = getControl(controls, "Overlap") / 100.0 * stem
  xHeight = getControl(controls, "Crossbar Height") / 100.0 * capHeight
  newX = drawAngledRectangle(0, capHeight, stem, -capHeight,angle)
  drawAngledRectangle(newX*2 - overlap, capHeight, stem, -capHeight,-angle)
  xbarOffset = tan(pi-angle)*xHeight
  xbarLen = tan(pi-angle)*(capHeight-(xHeight+crossbar))*2 - overlap
  drawRectangle(xbarOffset, xHeight + crossbar/2, xbarLen, crossbar)
  Glyphs.font.selectedLayers[0].LSB = Glyphs.font.selectedLayers[0].RSB = 5
  Glyphs.font.selectedLayers[0].removeOverlap() 
Example 55
Project: GlyphsScripts   Author: simoncozens   File: Sansomatic.py    MIT License 5 votes vote down vote up
def N(controls):
  angle = getControl(controls, "Angle")

  stem = getDimension("HV")
  newX = drawAngledRectangle(0, 0, stem, capHeight,angle)
  width = tan(angle)*capHeight + stemWidthForTargetWeight(stem,angle)
  drawRectangle(newX+(stemWidthForTargetWeight(stem,angle)-stem), 0,stem,capHeight)
  drawRectangle(0, 0,stem,capHeight)
  Glyphs.font.selectedLayers[0].LSB = Glyphs.font.selectedLayers[0].RSB = 50
  Glyphs.font.selectedLayers[0].removeOverlap() 
Example 56
Project: GlyphsScripts   Author: simoncozens   File: Sansomatic.py    MIT License 5 votes vote down vote up
def Z(controls):
  angle = getControl(controls, "Angle")

  stem = getDimension("HV")
  crossbar = getDimension("HH")
  newX = drawAngledRectangle(0, 0, stem, capHeight,-angle)
  offset = tan(angle)*crossbar
  width = tan(angle)*capHeight + stemWidthForTargetWeight(stem,angle)
  drawRectangle(newX+offset, 0,width-offset,crossbar)
  drawRectangle(newX, capHeight-crossbar,width-offset,crossbar)
  Glyphs.font.selectedLayers[0].LSB = Glyphs.font.selectedLayers[0].RSB = 5
  Glyphs.font.selectedLayers[0].removeOverlap() 
Example 57
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_quadpack.py    GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        if sys.platform == 'win32':
            file = ctypes.util.find_msvcrt()
        elif sys.platform == 'darwin':
            file = 'libm.dylib'
        else:
            file = 'libm.so'
        self.lib = ctypes.CDLL(file)
        restype = ctypes.c_double
        argtypes = (ctypes.c_double,)
        for name in ['sin', 'cos', 'tan']:
            func = getattr(self.lib, name)
            func.restype = restype
            func.argtypes = argtypes 
Example 58
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_quadpack.py    GNU General Public License v3.0 5 votes vote down vote up
def test_typical(self):
        assert_quad(quad(self.lib.sin,0,5),quad(math.sin,0,5)[0])
        assert_quad(quad(self.lib.cos,0,5),quad(math.cos,0,5)[0])
        assert_quad(quad(self.lib.tan,0,1),quad(math.tan,0,1)[0])

    #@dec.skipif(_ctypes_missing, msg="Ctypes library could not be found")
    # This doesn't seem to always work.  Need a better way to figure out
    # whether the fast path is called. 
Example 59
Project: SGVHAK_Rover   Author: Roger-random   File: roverchassis.py    MIT License 5 votes vote down vote up
def calculate_radius_min_max(self):
    """
    Once the wheel configuraton has been loaded, read maximum turning ability
    of the wheels and calculate the minimum turning radius. Also look at the
    radius when the wheels are turned a single degree and use that as maximum
    turning radius.

    Initial values are established by first finding the wheel with the
    greatest X distance from center. Minimum radius is 1% of its distance, and
    maximum is 10 times (1000%) of the distance.
    """
    wheel_x_max = 0
    for wheel in self.wheels.values():
      if abs(wheel.x) > wheel_x_max:
        wheel_x_max = abs(wheel.x)

    if wheel_x_max > 0:
      limit_min = wheel_x_max * 0.01
      limit_max = wheel_x_max * 10

    # Initial values established, now let's look at each wheel and calculate
    # its relative min/max and compare against initial values.
    for wheel in self.wheels.values():
      if wheel.steeringcontrol:
        angle_max = wheel.steeringcontrol.maxangle(wheel.steeringparam)
        if angle_max < 90:
          limit_radius = wheel.x + (wheel.y/math.tan(math.radians(angle_max)))
          if limit_radius > limit_min:
            limit_min = limit_radius
          # If the rover uses steering mechanism that can be more precise than
          # +/- one degree, decrease the value accordingly.
          limit_radius = wheel.x + (wheel.y/math.tan(math.radians(1)))
          if abs(limit_radius) < limit_max:
            limit_max = abs(limit_radius)

    self.minRadius = limit_min
    self.maxRadius = limit_max 
Example 60
Project: kutils   Author: subpic   File: image_utils.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 61
Project: TransferbilityFromAttributionMaps   Author: zju-vipa   File: task_viz.py    MIT License 5 votes vote down vote up
def get_K(resolution, fov):
    resolution, _ = resolution
    focal_length = 1. / ( 2 * math.tan( fov / 2. ) ) 
    focal_length *= resolution
    offset = resolution /2.
    K = np.array(
        ((   focal_length,    0, offset),
        (    0  ,  focal_length, offset),
        (    0  ,  0,      1       )), dtype=np.float64)
    K[:,1] = -K[:,1]
    K[:,2] = -K[:,2]
    return K 
Example 62
Project: asciimatics   Author: peterbrittain   File: maps.py    Apache License 2.0 5 votes vote down vote up
def _convert_latitude(self, latitude):
        """Convert from latitude to the y position in overall map."""
        return int((180 - (180 / pi * log(tan(
            pi / 4 + latitude * pi / 360)))) * (2 ** self._zoom) * self._size / 360) 
Example 63
Project: PokemonGo-Bot   Author: PokemonGoF   File: utils.py    MIT License 5 votes vote down vote up
def lat2y(lat):
    lat = min(89.5, max(lat, -89.5))
    phi = deg2rad(lat)
    sinphi = sin(phi)
    con = ECCENT * sinphi
    con = pow((1.0 - con) / (1.0 + con), COM)
    ts = tan(0.5 * (pi * 0.5 - phi)) / con
    return 0 - EARTH_RADIUS_MAJ * log(ts) 
Example 64
Project: SherpaHighLevel   Author: Shedino   File: mavextra.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def rate_of_turn(speed, bank):
    '''return expected rate of turn in degrees/s for given speed in m/s and
       bank angle in degrees'''
    if abs(speed) < 2 or abs(bank) > 80:
        return 0
    ret = degrees(9.81*tan(radians(bank))/speed)
    return ret 
Example 65
Project: SherpaHighLevel   Author: Shedino   File: mavextra.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def gps_velocity_body(GPS_RAW_INT, ATTITUDE):
    '''return GPS velocity vector in body frame'''
    r = rotation(ATTITUDE)
    return r.transposed() * Vector3(GPS_RAW_INT.vel*0.01*cos(radians(GPS_RAW_INT.cog*0.01)),
                                    GPS_RAW_INT.vel*0.01*sin(radians(GPS_RAW_INT.cog*0.01)),
                                    -tan(ATTITUDE.pitch)*GPS_RAW_INT.vel*0.01) 
Example 66
Project: SherpaHighLevel   Author: Shedino   File: mavextra.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def rate_of_turn(speed, bank):
    '''return expected rate of turn in degrees/s for given speed in m/s and
       bank angle in degrees'''
    if abs(speed) < 2 or abs(bank) > 80:
        return 0
    ret = degrees(9.81*tan(radians(bank))/speed)
    return ret 
Example 67
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 5 votes vote down vote up
def _transform(b, a, Wn, analog, output):
    """
    Shift prototype filter to desired frequency, convert to digital with
    pre-warping, and return in various formats.
    """
    Wn = np.asarray(Wn)
    if not analog:
        if np.any(Wn < 0) or np.any(Wn > 1):
            raise ValueError("Digital filter critical frequencies "
                             "must be 0 <= Wn <= 1")
        fs = 2.0
        warped = 2 * fs * tan(pi * Wn / fs)
    else:
        warped = Wn

    # Shift frequency
    b, a = lp2lp(b, a, wo=warped)

    # Find discrete equivalent if necessary
    if not analog:
        b, a = bilinear(b, a, fs=fs)

    # Transform to proper out type (pole-zero, state-space, numer-denom)
    if output in ('zpk', 'zp'):
        return tf2zpk(b, a)
    elif output in ('ba', 'tf'):
        return b, a
    elif output in ('ss', 'abcd'):
        return tf2ss(b, a)
    elif output in ('sos'):
        raise NotImplementedError('second-order sections not yet implemented')
    else:
        raise ValueError('Unknown output type {0}'.format(output)) 
Example 68
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 5 votes vote down vote up
def latlontopixels(lat, lon, zoom):
    mx = (lon * ORIGIN_SHIFT) / 180.0
    my = log(tan((90 + lat) * pi/360.0))/(pi/180.0)
    my = (my * ORIGIN_SHIFT) /180.0
    res = INITIAL_RESOLUTION / (2**zoom)
    px = (mx + ORIGIN_SHIFT) / res
    py = (my + ORIGIN_SHIFT) / res
    return px, py 
Example 69
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 5 votes vote down vote up
def counterSink(self, part, diameter, angle, points, boreDepth=0):
        if boreDepth < 0:
            boreDepth = 0
        r = diameter / 2.0
        h = r / math.tan(math.radians(angle / 2.0))
        for point in points:
            if type(point) is tuple or type(point) is list:
                point = Base.Vector(point[0], point[1], point[2])
            sink = Part.makeCone(0,r, h, point)
            sink.translate(Base.Vector(0,0,-h-boreDepth))
            part = part.cut(sink)
        return part 
Example 70
Project: PySail-426   Author: j3b4   File: SimulazioneRegata300.py    GNU General Public License v3.0 5 votes vote down vote up
def DisegnaFincature(self):
        self.Graficodx.delete(ALL)
        #self.Graficosx.delete("icona")
        NW=self.Bbox[0]#angolo NW
        SE=self.Bbox[1]#angolo SE
        N=25
        height=float(self.Graficodx.cget("height"))
        width=float(self.Graficodx.cget("width"))
        Df=math.log(math.tan(SE[0]/2+math.pi/4)/math.tan(NW[0]/2+math.pi/4),math.e)
        self.q=math.copysign((NW[0]-SE[0])/Df,1)
        self.FattoreDiScala=0.85*min(height/math.copysign((NW[0]-SE[0]),1),width/(self.q*math.copysign((NW[1]-SE[1]),1)))
        lat=NW[0]
        passo=(NW[0]-SE[0])*1.0/N
        for i in range(0,N+1):
            self.disegna([(lat,NW[1]),(lat,SE[1])],"darkgray","fincature")#orizontali
            lat=lat-passo
        lon=NW[1]
        passo=(NW[1]-SE[1])*1.0/N
        for i in range(0,N+1):
            self.disegna([(NW[0],lon),(SE[0],lon)],"darkgray","fincature")#verticali
            lon=lon-passo
        testo=stampalat(NW[0])
        x=-NW[1]*self.FattoreDiScala*self.q
        y=-NW[0]*self.FattoreDiScala
        self.Graficodx.create_text(x-5,y-15,text=testo,fill="darkgray",tags="fincature",anchor="e", font=MIOFONT)
        testo=stampalon(NW[1])
        self.Graficodx.create_text(x-5,y,text=testo,fill="darkgray",tags="fincature",anchor="e", font=MIOFONT)
        testo=stampalat(SE[0])
        x=-SE[1]*self.FattoreDiScala*self.q
        y=-SE[0]*self.FattoreDiScala
        self.Graficodx.create_text(x+5,y,text=testo,fill="darkgray",tags="fincature",anchor="w", font=MIOFONT)
        testo=stampalon(SE[1])
        self.Graficodx.create_text(x+5,y+15,text=testo,fill="darkgray",tags="fincature",anchor="w", font=MIOFONT)
        x1=-self.Partenza[1]*self.FattoreDiScala*self.q
        y1=-self.Partenza[0]*self.FattoreDiScala
        self.Graficodx.create_rectangle(x1-3,y1-3,x1+3,y1+3,fill="red",tags="fincature")
        x2=-self.Arrivo[1]*self.FattoreDiScala*self.q
        y2=-self.Arrivo[0]*self.FattoreDiScala
        self.Graficodx.create_rectangle(x2-3,y2-3,x2+3,y2+3,fill="green",tags="fincature")
        self.Graficodx.create_line(x1,y1,x2,y2,fill=BGCOLOR,tags="fincature") 
Example 71
Project: PySail-426   Author: j3b4   File: SimulazioneRegata316.py    GNU General Public License v3.0 5 votes vote down vote up
def CalcolaFattoreDiScala(self):
        NW=self.Bbox[0]#angolo NW
        SE=self.Bbox[1]#angolo SE
        height=float(self.Graficodx.cget("height"))
        width=float(self.Graficodx.cget("width"))
        Df=math.log(math.tan(SE[0]/2+math.pi/4)/math.tan(NW[0]/2+math.pi/4),math.e)
        self.q=math.copysign((NW[0]-SE[0])/Df,1)
        self.FattoreDiScala=0.85*min(height/math.copysign((NW[0]-SE[0]),1),width/(self.q*math.copysign((NW[1]-SE[1]),1))) 
Example 72
Project: PySail-426   Author: j3b4   File: ModuloBarca02.py    GNU General Public License v3.0 5 votes vote down vote up
def Randa(self):
        aw=self.AW()
        awa=aw[1]
        randa=[]
        if awa>0:
            segno=1
        else:
            segno=-1
        awa=math.copysign(awa,1)
        l=110
        zero=35
        alfa0=10#integer
        r=0.5*l/math.tan(math.radians(alfa0))
        if self.Speed()<=0 or awa<=math.radians(alfa0):
            randa=[(0,35.0),(0,-75.0)]
        else:
            beta=awa-math.radians(5)
            if beta>0.5*math.pi:
                beta=0.5*math.pi
            cx=segno*r*math.cos(beta+math.radians(alfa0))
            cy=zero-r*math.sin(beta+math.radians(alfa0))
            betaint=int(math.degrees(beta)+0.5)
            for angolo in range(betaint-alfa0,betaint+alfa0):
                angolo=math.radians(angolo)
                x=cx-r*segno*math.cos(angolo)
                y=cy+r*math.sin(angolo)
                randa.append((x,y))
        return randa
#FUNZIONI 
Example 73
Project: PySail-426   Author: j3b4   File: ModuloNav.py    GNU General Public License v3.0 5 votes vote down vote up
def puntodistanterotta(latA,lonA,Distanza,Rotta):
    #non funziona in prossimita' dei poli
    #dove può risultare latC>90, log(tan(latC/...))=log(<0)   (*)
    a=Distanza*1.0/RaggioTerrestre
    latB=latA+a*math.cos(Rotta)
    if math.copysign(latA-latB,1)<=math.radians(0.1/3600.0):
        q=math.cos(latA)
    else:
        Df=math.log(math.tan(latB/2+math.pi/4)/math.tan(latA/2+math.pi/4),math.e)#(*)
        q=(latB-latA)/Df
    lonB=lonA-a*math.sin(Rotta)/q
    return latB,lonB 
Example 74
Project: PySail-426   Author: j3b4   File: ModuloNav.py    GNU General Public License v3.0 5 votes vote down vote up
def lossodromica(latA,lonA,latB,lonB):
    #non funziona in prossimita' dei poli
    #per latB=-90: math domain error log(0)
    #per latA=-90 [zero divison error]
    #per A==B ritorna (0.0,0.0)
    #if latA==latB:
    if  math.copysign(latA-latB,1)<=math.radians(0.1/3600.0):
        q=math.cos(latA)
    else:
        Df=math.log(math.tan(latB/2+math.pi/4)/math.tan(latA/2+math.pi/4),math.e)
        q=(latB-latA)*1.0/Df
    Distanza=RaggioTerrestre*((latA-latB)**2+(q*(lonA-lonB))**2)**0.5
    Rotta=math.atan2(-q*(lonB-lonA),(latB-latA))
    if Rotta<0:Rotta=Rotta+2.0*math.pi#atan2:[-pi,pi]
    return Distanza,Rotta 
Example 75
Project: PySail-426   Author: j3b4   File: ModuloBarca02.py    GNU General Public License v3.0 5 votes vote down vote up
def Randa(self):
        aw=self.AW()
        awa=aw[1]
        randa=[]
        if awa>0:
            segno=1
        else:
            segno=-1
        awa=math.copysign(awa,1)
        l=110
        zero=35
        alfa0=10#integer
        r=0.5*l/math.tan(math.radians(alfa0))
        if self.Speed()<=0 or awa<=math.radians(alfa0):
            randa=[(0,35.0),(0,-75.0)]
        else:
            beta=awa-math.radians(5)
            if beta>0.5*math.pi:
                beta=0.5*math.pi
            cx=segno*r*math.cos(beta+math.radians(alfa0))
            cy=zero-r*math.sin(beta+math.radians(alfa0))
            betaint=int(math.degrees(beta)+0.5)
            for angolo in range(betaint-alfa0,betaint+alfa0):
                angolo=math.radians(angolo)
                x=cx-r*segno*math.cos(angolo)
                y=cy+r*math.sin(angolo)
                randa.append((x,y))
        return randa
#FUNZIONI 
Example 76
Project: aiv-python   Author: aiv01   File: software_renderer.py    GNU General Public License v2.0 5 votes vote down vote up
def project(self, window, translate, fov):
        # distance from camera
        d = math.tan(math.radians(fov/2.0))
        v = self.v + translate
        self.projected = Vector3(0.0, 0.0, 0.0)
        self.projected.y = v.y / (d * v.z)
        self.projected.x = v.x / (window.aspect_ratio * d * v.z)
        self.projected.z = v.z

        self.projected.x = (self.projected.x * window.width / 2.0) + (window.width / 2.0)
        self.projected.y = -(self.projected.y * window.height / 2.0) + (window.height / 2.0)

        # compute lambert
        light_direction = (Vector3(0.0, 10.0, -3) - self.v).normalized
        self.lambert = max(light_direction.dot(self.n), 0) 
Example 77
Project: building-boundary   Author: Geodan   File: segment.py    MIT License 4 votes vote down vote up
def regularize(self, orientation, max_error=None):
        """
        Recreates the line segment based on the given orientation.

        Parameters
        ----------
        orientation : float or int
            The orientation the line segment should have. In radians from
            0 to pi (east to west counterclockwise) and
            0 to -pi (east to west clockwise).
        max_error : float or int
            The maximum error (max distance points to line) the
            fitted line is allowed to have. A ThresholdError will be
            raised if this max error is exceeded.

        Raises
        ------
        ThresholdError
            If the error of the fitted line (max distance points to
            line) exceeds the given max error.

        .. [1] https://math.stackexchange.com/questions/1377716/how-to-find-a-least-squares-line-with-a-known-slope  # noqa
        """
        prev_a = self.a
        prev_b = self.b
        prev_c = self.c

        if not np.isclose(orientation, self.orientation):
            if np.isclose(abs(orientation), math.pi / 2):
                self.a = 1
                self.b = 0
                self.c = np.mean(self.points[:, 0])
            elif (np.isclose(abs(orientation), math.pi) or
                    np.isclose(orientation, 0)):
                self.a = 0
                self.b = 1
                self.c = np.mean(self.points[:, 1])
            else:
                self.a = math.tan(orientation)
                self.b = -1
                self.c = (sum(self.points[:, 1] - self.a * self.points[:, 0]) /
                          len(self.points))

            if max_error is not None:
                error = self.error()
                if error > max_error:
                    self.a = prev_a
                    self.b = prev_b
                    self.c = prev_c
                    raise utils.error.ThresholdError(
                        "Could not fit a proper line. Error: {}".format(error)
                    )

            self._create_line_segment() 
Example 78
Project: AxiSurface   Author: patriciogonzalezvivo   File: Arc.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def center(self):
        return  self.start + (self.end - self.start) * 0.5


    # @property
    # def bounds(self):
    #     """returns a bounding box for the segment in the form
    #     (xmin, xmax, ymin, ymax)."""
    #     # a(t) = radians(self.theta + self.delta*t)
    #     #      = (2*pi/360)*(self.theta + self.delta*t)
    #     # x'=0: ~~~~~~~~~
    #     # -rx*cos(phi)*sin(a(t)) = ry*sin(phi)*cos(a(t))
    #     # -(rx/ry)*cot(phi)*tan(a(t)) = 1
    #     # a(t) = arctan(-(ry/rx)tan(phi)) + pi*k === atan_x
    #     # y'=0: ~~~~~~~~~~
    #     # rx*sin(phi)*sin(a(t)) = ry*cos(phi)*cos(a(t))
    #     # (rx/ry)*tan(phi)*tan(a(t)) = 1
    #     # a(t) = arctan((ry/rx)*cot(phi))
    #     # atanres = arctan((ry/rx)*cot(phi)) === atan_y
    #     # ~~~~~~~~
    #     # (2*pi/360)*(self.theta + self.delta*t) = atanres + pi*k
    #     # Therfore, for both x' and y', we have...
    #     # t = ((atan_{x/y} + pi*k)*(360/(2*pi)) - self.theta)/self.delta
    #     # for all k s.t. 0 < t < 1

    #     if math.cos(self.phi) == 0:
    #         atan_x = math.pi/2
    #         atan_y = 0
    #     elif math.sin(self.phi) == 0:
    #         atan_x = 0
    #         atan_y = math.pi/2
    #     else:
    #         rx, ry = self.radius
    #         atan_x = math.atan(-(ry/rx)*math.tan(self.phi))
    #         atan_y = math.atan((ry/rx)/math.tan(self.phi))

    #     def angle_inv(ang, k):  # inverse of angle from Arc.derivative()
    #         return ((ang + pi*k)*(360/(2*pi)) - self.theta)/self.delta

    #     xtrema = [self.start[0], self.end[0]]
    #     ytrema = [self.start[1], self.end[1]]

    #     for k in range(-4, 5):
    #         tx = angle_inv(atan_x, k)
    #         ty = angle_inv(atan_y, k)
    #         if 0 <= tx <= 1:
    #             xtrema.append(self.getPointPct(tx)[0])
    #         if 0 <= ty <= 1:
    #             ytrema.append(self.getPointPct(ty)[1])
    #     xmin = max(xtrema)

    #     bbox = Bbox()
    #     bbox.min_x = min(xtrema)
    #     bbox.max_x = max(xtrema)
    #     bbox.min_y = min(ytrema)
    #     bbox.max_x = max(ytrema)
    #     return bbox 
Example 79
Project: wallgen   Author: SubhrajitPrusty   File: shapes.py    MIT License 4 votes vote down vote up
def genHexagon(width, height, img, outl=None, pic=False, per=1):

	per = 11-per
	x = y = 0
	
	radius = int(per/100.0 * min(height, width))

	idata = img.load() # load pixel data
	draw = ImageDraw.Draw(img)

	ang = 2 * math.pi / 6 # angle inside a hexagon
	apothem = radius * math.cos(math.pi/6) # radius of inner circle
	side = 2 * apothem * math.tan(math.pi/6) # length of each side
	hexwidth = 2 * apothem # horizontal width of a hexagon
	wboxes = width // int(hexwidth) # adj
	hboxes = height // int((side + radius) * 0.75)  # adj
	
	xback = 0 # backup of x 
	x,y = xback+apothem, -(side/2) # start here


	if pic:
		hboxes+=1

	for i in range(-1, hboxes+1):
		for j in range(-1, wboxes+2):
			points = [((x + radius * math.sin(k * ang)), (y + radius * math.cos(k * ang))) for k in range(6)]

			a,b = x,y
			try: # adj to not overflow
				b = b - side//2 if b>=height else b
				b = b + side//2 if b<=0 else b

				a = a - radius if a>=width else a
				a = a + radius if a<=0 else a

				c = idata[a,b]

			except Exception as e:
				# print(a,b)
				c = "#00ff00" # backup

			if outl:
				draw.polygon((points), fill=c, outline=outl) # draw one hexagon
			else:
				draw.polygon((points), fill=c) # draw one hexagon
			x += hexwidth

		y += radius + (side/2) # shift cursor vertically
		if i%2 == 0:
			x=xback+apothem # restore horizontal starting point
		else:
			x=xback # restore horizontal starting point, but for honeycombing

	return img # return final image

#############
# ISOMETRIC #
############# 
Example 80
Project: carla-training-data   Author: enginBozkurt   File: settings.py    MIT License 4 votes vote down vote up
def make_carla_settings(args):
    """Make a CarlaSettings object with the settings we need."""
    settings = CarlaSettings()
    settings.set(
        SynchronousMode=False,
        SendNonPlayerAgentsInfo=True,
        NumberOfVehicles=NUM_VEHICLES,
        NumberOfPedestrians=NUM_PEDESTRIANS,
        WeatherId=random.choice([1, 3, 7, 8, 14]),
        QualityLevel=args.quality_level)
    settings.randomize_seeds()
    camera0 = sensor.Camera('CameraRGB')
    camera0.set_image_size(WINDOW_WIDTH, WINDOW_HEIGHT)
    camera0.set_position(0, 0.0, CAMERA_HEIGHT_POS)
    camera0.set_rotation(0.0, 0.0, 0.0)
    settings.add_sensor(camera0)

    lidar = sensor.Lidar('Lidar32')
    lidar.set_position(0, 0.0, LIDAR_HEIGHT_POS)
    lidar.set_rotation(0, 0, 0)
    lidar.set(
        Channels=40,
        Range=MAX_RENDER_DEPTH_IN_METERS,
        PointsPerSecond=720000,
        RotationFrequency=10,
        UpperFovLimit=7,
        LowerFovLimit=-16)
    settings.add_sensor(lidar)
    """ Depth camera for filtering out occluded vehicles """
    depth_camera = sensor.Camera('DepthCamera', PostProcessing='Depth')
    depth_camera.set(FOV=90.0)
    depth_camera.set_image_size(WINDOW_WIDTH, WINDOW_HEIGHT)
    depth_camera.set_position(0, 0, CAMERA_HEIGHT_POS)
    depth_camera.set_rotation(0, 0, 0)
    settings.add_sensor(depth_camera)
    # (Intrinsic) K Matrix
    # | f 0 Cu
    # | 0 f Cv
    # | 0 0 1
    # (Cu, Cv) is center of image
    k = np.identity(3)
    k[0, 2] = WINDOW_WIDTH_HALF
    k[1, 2] = WINDOW_HEIGHT_HALF
    f = WINDOW_WIDTH / \
        (2.0 * math.tan(90.0 * math.pi / 360.0))
    k[0, 0] = k[1, 1] = f
    camera_to_car_transform = camera0.get_unreal_transform()
    lidar_to_car_transform = lidar.get_transform(
    ) * Transform(Rotation(yaw=90), Scale(z=-1))
    return settings, k, camera_to_car_transform, lidar_to_car_transform