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 6 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