Python math.atan() Examples

The following are code examples for showing how to use math.atan(). 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: CozmoCommander   Author: cozmobotics   File: CozmoCommander.py    Apache License 2.0 6 votes vote down vote up
def angle360 (DeltaX, DeltaY):
	if (math.fabs(DeltaX) > 0.01):			# avoid division by 0
		Angle = math.fabs(DeltaY)/math.fabs(DeltaX)
		Angle = math.atan(Angle)
		Angle = math.degrees (Angle)
		# print (Angle)
	else:
		Angle = 90.0
	
	if   ((DeltaX > 0) and (DeltaY > 0)):
		pass
	elif ((DeltaX > 0) and (DeltaY < 0)):
		Angle = 360.0 - Angle
	elif ((DeltaX < 0) and (DeltaY > 0)):
		Angle = 180.0 - Angle
	elif ((DeltaX < 0) and (DeltaY < 0)):
		Angle = 180.0 + Angle
	return (Angle)
	
# ------------------------------------------------------------------- 
Example 2
Project: soccer-matlab   Author: utra-robosoccer   File: pointCloudFromCameraImage.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def getRayFromTo(mouseX,mouseY):
        width, height, viewMat, projMat, cameraUp, camForward, horizon,vertical, _,_,dist, camTarget = p.getDebugVisualizerCamera()
        camPos = [camTarget[0] - dist*camForward[0],camTarget[1] - dist*camForward[1],camTarget[2] - dist*camForward[2]]
        farPlane = 10000
        rayForward = [(camTarget[0]-camPos[0]),(camTarget[1]-camPos[1]),(camTarget[2]-camPos[2])]
        lenFwd = math.sqrt(rayForward[0]*rayForward[0]+rayForward[1]*rayForward[1]+rayForward[2]*rayForward[2])
        invLen = farPlane*1./lenFwd
        rayForward = [invLen*rayForward[0],invLen*rayForward[1],invLen*rayForward[2]]
        rayFrom = camPos
        oneOverWidth = float(1)/float(width)
        oneOverHeight = float(1)/float(height)

        dHor = [horizon[0] * oneOverWidth,horizon[1] * oneOverWidth,horizon[2] * oneOverWidth]
        dVer = [vertical[0] * oneOverHeight,vertical[1] * oneOverHeight,vertical[2] * oneOverHeight]
        rayToCenter=[rayFrom[0]+rayForward[0],rayFrom[1]+rayForward[1],rayFrom[2]+rayForward[2]]
        ortho=[- 0.5 * horizon[0] + 0.5 * vertical[0]+float(mouseX)*dHor[0]-float(mouseY)*dVer[0],
             - 0.5 * horizon[1] + 0.5 * vertical[1]+float(mouseX)*dHor[1]-float(mouseY)*dVer[1],
             - 0.5 * horizon[2] + 0.5 * vertical[2]+float(mouseX)*dHor[2]-float(mouseY)*dVer[2]]

        rayTo = [rayFrom[0]+rayForward[0]  +ortho[0],
                                        rayFrom[1]+rayForward[1]  +ortho[1],
                                        rayFrom[2]+rayForward[2]  +ortho[2]]
        lenOrtho = math.sqrt(ortho[0]*ortho[0]+ortho[1]*ortho[1]+ortho[2]*ortho[2])
        alpha = math.atan(lenOrtho/farPlane)
        return rayFrom,rayTo, alpha 
Example 3
Project: chattR   Author: patrickstocklin   File: zoom.py    GNU General Public License v2.0 6 votes vote down vote up
def pixel_to_lonlat(self, px, zoom):
        "Converts a pixel to a longitude, latitude pair at the given zoom level."
        if len(px) != 2:
            raise TypeError('Pixel should be a sequence of two elements.')

        # Getting the number of pixels for the given zoom level.
        npix = self._npix[zoom]

        # Calculating the longitude value, using the degrees per pixel.
        lon = (px[0] - npix) / self._degpp[zoom]

        # Calculating the latitude value.
        lat = RTOD * (2 * atan(exp((px[1] - npix) / (-1.0 * self._radpp[zoom]))) - 0.5 * pi)

        # Returning the longitude, latitude coordinate pair.
        return (lon, lat) 
Example 4
Project: Deep-Learning-Cone-Beam-CT   Author: ma0ho   File: ct.py    Apache License 2.0 6 votes vote down vote up
def init_parker_1D( config, beta, delta ):
    assert( beta + nm.eps >= 0 )

    w = np.ones( ( config.proj_shape.W ), dtype = np.float32 )

    for u in range( 0, config.proj_shape.W ):
        # current fan angle
        alpha = math.atan( ( u+0.5 - config.proj_shape.W/2 ) *
                config.pixel_shape.W / config.source_det_distance )

        if beta >= 0 and beta < 2 * (delta+alpha):
            # begin of scan
            w[u] = math.pow( math.sin( math.pi/4 * ( beta / (delta+alpha) ) ), 2 )
        elif beta >= math.pi + 2*alpha and beta < math.pi + 2*delta:
            # end of scan
            w[u] = math.pow( math.sin( math.pi/4 * ( ( math.pi + 2*delta - beta
                ) / ( delta - alpha ) ) ), 2 )
        elif beta >= math.pi + 2*delta:
            # out of range
            w[u] = 0.0

    return w 
Example 5
Project: TESTGIT   Author: B-ROY   File: zoom.py    Apache License 2.0 6 votes vote down vote up
def pixel_to_lonlat(self, px, zoom):
        "Converts a pixel to a longitude, latitude pair at the given zoom level."
        if len(px) != 2:
            raise TypeError('Pixel should be a sequence of two elements.')

        # Getting the number of pixels for the given zoom level.
        npix = self._npix[zoom]

        # Calculating the longitude value, using the degrees per pixel.
        lon = (px[0] - npix) / self._degpp[zoom]

        # Calculating the latitude value.
        lat = RTOD * ( 2 * atan(exp((px[1] - npix)/ (-1.0 * self._radpp[zoom]))) - 0.5 * pi)

        # Returning the longitude, latitude coordinate pair.
        return (lon, lat) 
Example 6
Project: AneMo   Author: jspargo   File: zoom.py    GNU General Public License v2.0 6 votes vote down vote up
def pixel_to_lonlat(self, px, zoom):
        "Converts a pixel to a longitude, latitude pair at the given zoom level."
        if len(px) != 2:
            raise TypeError('Pixel should be a sequence of two elements.')

        # Getting the number of pixels for the given zoom level.
        npix = self._npix[zoom]

        # Calculating the longitude value, using the degrees per pixel.
        lon = (px[0] - npix) / self._degpp[zoom]

        # Calculating the latitude value.
        lat = RTOD * (2 * atan(exp((px[1] - npix) / (-1.0 * self._radpp[zoom]))) - 0.5 * pi)

        # Returning the longitude, latitude coordinate pair.
        return (lon, lat) 
Example 7
Project: GTDWeb   Author: lanbing510   File: zoom.py    GNU General Public License v2.0 6 votes vote down vote up
def pixel_to_lonlat(self, px, zoom):
        "Converts a pixel to a longitude, latitude pair at the given zoom level."
        if len(px) != 2:
            raise TypeError('Pixel should be a sequence of two elements.')

        # Getting the number of pixels for the given zoom level.
        npix = self._npix[zoom]

        # Calculating the longitude value, using the degrees per pixel.
        lon = (px[0] - npix) / self._degpp[zoom]

        # Calculating the latitude value.
        lat = RTOD * (2 * atan(exp((px[1] - npix) / (-1.0 * self._radpp[zoom]))) - 0.5 * pi)

        # Returning the longitude, latitude coordinate pair.
        return (lon, lat) 
Example 8
Project: Reinforcement-Learning-for-Self-Driving-Cars   Author: songyanho   File: gauge.py    Apache License 2.0 6 votes vote down vote up
def _thick_line(self, start_point, end_point, fill, thickness):
        """Draws a line using polygons to give it a thickness"""

        if thickness == 1:
            self.line((start_point, end_point), fill=fill)
        else:
            # Angle of the line
            if end_point[0] == start_point[0]:
                # Catch a division by zero error
                a = math.pi / 2
            else:
                a = math.atan((end_point[1] - start_point[1]) / (end_point[0] - start_point[0]))

            sin = math.sin(a)
            cos = math.cos(a)
            xdelta = sin * thickness / 2.0
            ydelta = cos * thickness / 2.0

            points = ((start_point[0] - xdelta, start_point[1] + ydelta),
                      (start_point[0] + xdelta, start_point[1] - ydelta),
                      (end_point[0] + xdelta, end_point[1] - ydelta),
                      (end_point[0] - xdelta, end_point[1] + ydelta))

            self.polygon(points, fill=fill) 
Example 9
Project: unicorn-hat-hd   Author: pimoroni   File: demo.py    MIT License 5 votes vote down vote up
def tunnel(x, y, step):
    speed = step / 100.0
    x -= (u_width / 2)
    y -= (u_height / 2)
    xo = math.sin(step / 27.0) * 2
    yo = math.cos(step / 18.0) * 2
    x += xo
    y += yo
    if y == 0:
        if x < 0:
            angle = -(math.pi / 2)
        else:
            angle = (math.pi / 2)
    else:
        angle = math.atan(x / y)
    if y > 0:
        angle += math.pi
    angle /= 2 * math.pi  # convert angle to 0...1 range
    hyp = math.sqrt(math.pow(x, 2) + math.pow(y, 2))
    shade = hyp / 2.1
    shade = 1 if shade > 1 else shade
    angle += speed
    depth = speed + (hyp / 10)
    col1 = hue_to_rgb[step % 255]
    col1 = (col1[0] * 0.8, col1[1] * 0.8, col1[2] * 0.8)
    col2 = hue_to_rgb[step % 255]
    col2 = (col2[0] * 0.3, col2[1] * 0.3, col2[2] * 0.3)
    col = col1 if int(abs(angle * 6.0)) % 2 == 0 else col2
    td = .3 if int(abs(depth * 3.0)) % 2 == 0 else 0
    col = (col[0] + td, col[1] + td, col[2] + td)
    col = (col[0] * shade, col[1] * shade, col[2] * shade)
    return (col[0] * 255, col[1] * 255, col[2] * 255) 
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 testAtan(self):
        self.assertRaises(TypeError, math.atan)
        self.ftest('atan(-1)', math.atan(-1), -math.pi/4)
        self.ftest('atan(0)', math.atan(0), 0)
        self.ftest('atan(1)', math.atan(1), math.pi/4)
        self.ftest('atan(inf)', math.atan(INF), math.pi/2)
        self.ftest('atan(-inf)', math.atan(NINF), -math.pi/2)
        self.assertTrue(math.isnan(math.atan(NAN))) 
Example 11
Project: pyblish-win   Author: pyblish   File: test_math.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testAtanh(self):
        self.assertRaises(TypeError, math.atan)
        self.ftest('atanh(0)', math.atanh(0), 0)
        self.ftest('atanh(0.5)', math.atanh(0.5), 0.54930614433405489)
        self.ftest('atanh(-0.5)', math.atanh(-0.5), -0.54930614433405489)
        self.assertRaises(ValueError, math.atanh, 1)
        self.assertRaises(ValueError, math.atanh, -1)
        self.assertRaises(ValueError, math.atanh, INF)
        self.assertRaises(ValueError, math.atanh, NINF)
        self.assertTrue(math.isnan(math.atanh(NAN))) 
Example 12
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 13
Project: streetview_objectmapping   Author: vlkryl   File: objectmapping.py    MIT License 5 votes vote down vote up
def MetersToLatLon( mx, my ):
    "Converts XY point from Spherical Mercator EPSG:4326 to lat/lon in WGS84 Datum"
    originShift = 2 * pi * 6378137 / 2.0
    lon = (mx / originShift) * 180.0
    lat = (my / originShift) * 180.0
    lat = 180 / pi * (2 * atan(exp(lat * pi / 180.0)) - pi / 2.0)
    return lat, lon


# haversine distance formula between two points specified by their GPS coordinates 
Example 14
Project: NAO   Author: AISTLAB   File: wsNaoVisionMT.py    MIT License 5 votes vote down vote up
def getSpaceBallDistance(self):
    thresh=self._threshBall.copy() #保护
    (x,y),r=self.getMinCircle(thresh)
    dist=0
    if r>0: #缩放转换函数
      dist=round(self._baseSize*0.054/math.atan(math.radians(47.64*r/self.IMGH)),2)
      if dist>50:dist*=1.1
    return dist 
Example 15
Project: nxt-sketcher   Author: simondolle   File: printer.py    MIT License 5 votes vote down vote up
def get_xy(alpha, beta, structure_settings):

    r = structure_settings.r  # short arm length (attached to the rotative axis)
    a = structure_settings.a  # long arm length
    s = structure_settings.s  # pen distance

    xa = structure_settings.xa #left short arm x
    xb = structure_settings.xb #right short arm x


    # d is the first short arm extremity
    xd = xa - r * math.sin(alpha)
    yd = r * math.cos(alpha)

    # e is the first short arm extremity
    xe = xb - r * math.sin(beta)
    ye = r * math.cos(beta)

    de = compute_distance(xd, yd, xe, ye)

    #theta is the angle formed by de and the left long arm
    cos_theta = de/float(2 * a)
    cos_theta = min(cos_theta, 1.0)
    cos_theta = max(cos_theta, -1.0)
    theta = math.acos(cos_theta)

    #gamma is the angle formed by an horizontal axis and de
    tan_gamma = (ye-yd)/float(xe-xd)
    gamma = math.atan(tan_gamma)

    #lambda is the angle formed by an horizontal axis and the left long arm
    lam = theta + gamma
    xt = xd + a * math.cos(lam) - s * math.sin(lam)
    yt = yd + a * math.sin(lam) + s * math.cos(lam)

    return xt, yt 
Example 16
Project: RLBotPack   Author: RLBot   File: penguin_bot.py    MIT License 5 votes vote down vote up
def to_rotation(self):
		v = Vector2(self.x, self.y)
		r = math.atan2(v.y, v.x)
		r2 = math.atan(self.z / v.len())
		# r2 = math.pi * 0.3
		return Vector2(r, r2) 
Example 17
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 18
Project: blender-tools   Author: vvoovv   File: osm_georeferencing.py    GNU General Public License v3.0 5 votes vote down vote up
def fromGeographic(self, lat, lon):
        lat = math.radians(lat)
        lon = math.radians(lon-self.lon)
        B = math.sin(lon) * math.cos(lat)
        x = 0.5 * self.k * self.radius * math.log((1.+B)/(1.-B))
        y = self.k * self.radius * ( math.atan(math.tan(lat)/math.cos(lon)) - self.latInRadians )
        return (x,y) 
Example 19
Project: blender-tools   Author: vvoovv   File: osm_georeferencing.py    GNU General Public License v3.0 5 votes vote down vote up
def toGeographic(self, x, y):
        x = x/(self.k * self.radius)
        y = y/(self.k * self.radius)
        D = y + self.latInRadians
        lon = math.atan(math.sinh(x)/math.cos(D))
        lat = math.asin(math.sin(D)/math.cosh(x))

        lon = self.lon + math.degrees(lon)
        lat = math.degrees(lat)
        return (lat, lon) 
Example 20
Project: xia2   Author: xia2   File: NMolLib.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def unit_cell_volume(cell_a, cell_b, cell_c, cell_alpha, cell_beta, cell_gamma):
    """From the unit cell constants, compute the volume of the unit cell in
    A^3. Note that it is assumed that the cell_alpha, cell_beta, cell_gamma,
    angles are in degrees and the cell lengths (a, b, c) are in A."""

    # convert angles to radians from degrees

    pi = 4.0 * math.atan(1.0)
    dtor = pi / 180.0

    # then compute the required sines and cosines

    ca = math.cos(dtor * cell_alpha)
    cb = math.cos(dtor * cell_beta)
    cc = math.cos(dtor * cell_gamma)

    # finally evaluate the volume - this is simply the volume of a
    # parallelopiped

    V = (
        cell_a
        * cell_b
        * cell_c
        * math.sqrt(1 - ca * ca - cb * cb - cc * cc + 2 * ca * cb * cc)
    )
    return V 
Example 21
Project: openrocketdoc   Author: open-aerospace   File: document.py    GNU General Public License v3.0 5 votes vote down vote up
def sweepangle(self):
        """**[°]** Angle the leading edge of the fin makes with respect to the
        body of the rocket.
        """
        if self._sweep is not None:
            return degrees(atan(self._sweep / self.span))
        return self._sweepangle 
Example 22
Project: chainer-gqn   Author: musyoku   File: functions.py    MIT License 5 votes vote down vote up
def compute_yaw_and_pitch(vec):
    x, y, z = vec
    norm = np.linalg.norm(vec)
    if z < 0:
        yaw = math.pi + math.atan(x / z)
    elif x < 0:
        yaw = math.pi * 2 + math.atan(x / z)
    else:
        yaw = math.atan(x / z)
    pitch = -math.asin(y / norm)
    return yaw, pitch 
Example 23
Project: chainer-gqn   Author: musyoku   File: functions.py    MIT License 5 votes vote down vote up
def compute_yaw_and_pitch(vec):
    x, y, z = vec
    norm = np.linalg.norm(vec)
    if z < 0:
        yaw = math.pi + math.atan(x / z)
    elif x < 0:
        yaw = math.pi * 2 + math.atan(x / z)
    else:
        yaw = math.atan(x / z)
    pitch = -math.asin(y / norm)
    return yaw, pitch 
Example 24
Project: chainer-gqn   Author: musyoku   File: functions.py    MIT License 5 votes vote down vote up
def compute_yaw_and_pitch(vec):
    x, y, z = vec
    norm = np.linalg.norm(vec)
    if z < 0:
        yaw = math.pi + math.atan(x / z)
    elif x < 0:
        yaw = math.pi * 2 + math.atan(x / z)
    else:
        yaw = math.atan(x / z)
    pitch = -math.asin(y / norm)
    return yaw, pitch 
Example 25
Project: gcogen   Author: gcogen   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def angle(x1, y1, x2, y2):
    if x1 == x2:
        return 90
    else:
        return math.atan((y2 - y1)/(x2 - x1))*180/math.pi 
Example 26
Project: gcogen   Author: gcogen   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def arc_center_angle(self, cen_x, cen_y, angle, cw = True):
        g_command = "G03 "
        if cw == True:
            g_command = "G02 "
        curr_x, curr_y = self.t.position()
        radius = math.sqrt((curr_x - cen_x)**2 + (curr_y - cen_y)**2)
        # slope of perpendicular line joining curr and cen
        m = -1*((cen_x - curr_x)/(cen_y - curr_y))
        # change the heading to turn the turtle
        self.t.setheading(math.atan(m)*180/math.pi)
        # draw arc angle
        self.arc_angle(radius, angle, cw) 
Example 27
Project: Deep-Learning-Cone-Beam-CT   Author: ma0ho   File: ct.py    Apache License 2.0 5 votes vote down vote up
def init_riess_1D( config, beta, delta ):
    projW = config.proj_shape.W
    pixW = config.pixel_shape.W
    sdDist = config.source_det_distance

    w = np.zeros( ( projW ), dtype = np.float32 )

    # overscan angle
    # TODO: incorrect of for less than short scan
    over = 2*delta

    def w1(b, a):
        x = math.pi + over - b
        y = over - 2*a
        z = math.pi/2 * (x/y)
        return math.pow(math.sin(z), 2)

    def w2(b, a):
        x = b
        y = over + 2*a
        z = math.pi/2 * (x/y)
        return math.pow(math.sin(z), 2)

    for u in range( 0, projW ):

        # fan angle corresponding to u
        alpha = math.atan( ( u+0.5 - projW/2 ) *
                pixW / sdDist )

        if math.pi + 2*delta <= beta and beta <= math.pi + over:
            w[u] = w1(beta, alpha)
        elif math.pi + 2*over - 2*delta <= beta and beta <= math.pi + over:
            w[u] = 2 - w1(beta, alpha)
        elif 0 <= beta and beta <= 2*delta + over:
            w[u] = w2(beta, alpha)
        elif 0 <= beta and beta <= -over - 2*delta:
            w[u] = 2 - w2(beta, alpha)
        else:
            w[u] = 1

    return w 
Example 28
Project: Deep-Learning-Cone-Beam-CT   Author: ma0ho   File: ct.py    Apache License 2.0 5 votes vote down vote up
def init_schaefer_1D( config, beta, delta ):
    projW = config.proj_shape.W
    pixW = config.pixel_shape.W
    sdDist = config.source_det_distance

    w = np.zeros( ( projW ), dtype = np.float32 )

    for u in range( 0, projW ):

        # fan angle corresponding to u
        alpha = math.atan( ( u+0.5 - projW/2 ) *
                pixW / sdDist )

        if beta >= math.pi + 2*alpha and beta < math.pi + delta:
            # end of scan
            w[u] = math.pow( math.sin( math.pi/2 * ( ( math.pi + 2*delta - beta
                ) / ( delta - 2*alpha ) ) ), 2 )
        elif beta >= math.pi + 2*delta - 2*alpha and beta <= math.pi + delta:
            w[u] = 2- ( math.pow( math.sin( math.pi/2 * ( ( math.pi + 2*delta - beta
                ) / ( delta - 2*alpha ) ) ), 2 ) )
        elif beta >= 0 and beta <= 2*alpha + delta:
            # begin of scan
            w[u] = math.pow( math.sin( math.pi/2 * ( beta / (delta + 2*alpha) ) ), 2 )
        elif beta >= 0 and beta <= -delta - 2*alpha:
            w[u] = 2- ( math.pow( math.sin( math.pi/2 * ( beta / (delta +
                2*alpha) ) ), 2 ) )
        else:
            # out of range
            w[u] = 1

    return w 
Example 29
Project: Deep-Learning-Cone-Beam-CT   Author: ma0ho   File: ct.py    Apache License 2.0 5 votes vote down vote up
def init_redundancy_3D( config, primary_angles_rad, weights_type = 'parker' ):
    pa = primary_angles_rad

    # normalize angles to [0, 2*pi]
    pa -= pa[0]
    pa = np.where( pa < 0, pa + 2*math.pi, pa )

    # find rotation such that max(angles) is minimal
    tmp = np.reshape( pa, ( pa.size, 1 ) ) - pa
    tmp = np.where( tmp < 0, tmp + 2*math.pi, tmp )
    pa = tmp[:, np.argmin( np.max( tmp, 0 ) )]

    # delta = maximum fan_angle
    delta = math.atan( ( float(config.proj_shape.W * config.pixel_shape.W) / 2 )
            / config.source_det_distance )

    if weights_type == 'parker':
        f = lambda pi: init_parker_1D( config, pi, delta )
    elif weights_type == 'riess':
        f = lambda pi: init_riess_1D( config, pi, delta )
    elif weights_type == 'schaefer':
        f = lambda pi: init_schaefer_1D( config, pi, delta )

    # go over projections
    w = [
            np.reshape(
                f( pa[i] ),
                ( 1, 1, config.proj_shape.W )
            )
            for i in range( 0, pa.size )
        ]

    w = np.concatenate( w )

    return w 
Example 30
Project: rai-python   Author: MarcToussaint   File: transformations.py    MIT License 5 votes vote down vote up
def shear_from_matrix(matrix):
    """Return shear angle, direction and plane from shear matrix.
    >>> 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))
    >>> S0 = shear_matrix(angle, direct, point, normal)
    >>> angle, direct, point, normal = shear_from_matrix(S0)
    >>> S1 = shear_matrix(angle, direct, point, normal)
    >>> is_same_transform(S0, S1)
    True
    """
    M = numpy.array(matrix, dtype=numpy.float64, copy=False)
    M33 = M[:3, :3]
    # normal: cross independent eigenvectors corresponding to the eigenvalue 1
    l, V = numpy.linalg.eig(M33)
    i = numpy.where(abs(numpy.real(l) - 1.0) < 1e-4)[0]
    if len(i) < 2:
        raise ValueError("No two linear independent eigenvectors found %s" % l)
    V = numpy.real(V[:, i]).squeeze().T
    lenorm = -1.0
    for i0, i1 in ((0, 1), (0, 2), (1, 2)):
        n = numpy.cross(V[i0], V[i1])
        l = vector_norm(n)
        if l > lenorm:
            lenorm = l
            normal = n
    normal /= lenorm
    # direction and angle
    direction = numpy.dot(M33 - numpy.identity(3), normal)
    angle = vector_norm(direction)
    direction /= angle
    angle = math.atan(angle)
    # point: eigenvector corresponding to eigenvalue 1
    l, V = numpy.linalg.eig(M)
    i = numpy.where(abs(numpy.real(l) - 1.0) < 1e-8)[0]
    if not len(i):
        raise ValueError("no eigenvector corresponding to eigenvalue 1")
    point = numpy.real(V[:, i[-1]]).squeeze()
    point /= point[3]
    return angle, direction, point, normal 
Example 31
Project: esys-pbi   Author: fsxfreak   File: visualizer_3d.py    MIT License 5 votes vote down vote up
def __init__(self,g_pool , focal_length ):
        super().__init__(g_pool , "Debug Visualizer", False)

        self.focal_length = focal_length
        self.image_width = 640 # right values are assigned in update
        self.image_height = 480

        camera_fov = math.degrees(2.0 * math.atan( self.image_height / (2.0 * self.focal_length)))
        self.trackball = Trackball(camera_fov)

    ############## MATRIX FUNCTIONS ############################## 
Example 32
Project: esys-pbi   Author: fsxfreak   File: visualizer_calibration.py    MIT License 5 votes vote down vote up
def __init__(self, g_pool, world_camera_intrinsics , cal_ref_points_3d, cal_observed_points_3d, eye_camera_to_world_matrix0 , cal_gaze_points0_3d, eye_camera_to_world_matrix1 = np.eye(4) , cal_gaze_points1_3d = [],  run_independently = False , name = "Calibration Visualizer" ):
		super().__init__( g_pool,name,  run_independently)

		self.image_width = 640 # right values are assigned in update
		self.focal_length = 620
		self.image_height = 480

		self.eye_camera_to_world_matrix0 = eye_camera_to_world_matrix0
		self.eye_camera_to_world_matrix1 = eye_camera_to_world_matrix1

		self.cal_ref_points_3d = cal_ref_points_3d
		self.cal_observed_points_3d = cal_observed_points_3d
		self.cal_gaze_points0_3d = cal_gaze_points0_3d
		self.cal_gaze_points1_3d = cal_gaze_points1_3d

		if world_camera_intrinsics:
			self.world_camera_width = world_camera_intrinsics['resolution'][0]
			self.world_camera_height = world_camera_intrinsics['resolution'][1]
			self.world_camera_focal = (world_camera_intrinsics['camera_matrix'][0][0] +  world_camera_intrinsics['camera_matrix'][1][1] ) / 2.0
		else:
			self.world_camera_width = 0
			self.world_camera_height = 0
			self.world_camera_focal = 0

		camera_fov = math.degrees(2.0 * math.atan( self.window_size[0] / (2.0 * self.focal_length)))
		self.trackball = Trackball(camera_fov)
		self.trackball.distance = [0,0,-80.]
		self.trackball.pitch = 210
		self.trackball.roll = 0


	########### Open, update, close ##################### 
Example 33
Project: esys-pbi   Author: fsxfreak   File: utils.py    MIT License 5 votes vote down vote up
def make_coord_system_eye_camera_based(window_size, focal_length ):
    camera_fov = math.degrees(2.0 * math.atan( window_size[1] / (2.0 * focal_length)))
    glMatrixMode( GL_PROJECTION )
    glLoadIdentity( )
    gluPerspective( camera_fov, float(window_size[0])/window_size[1], 0.1, 2000.0 )
    glMatrixMode( GL_MODELVIEW )
    glLoadIdentity( ) 
Example 34
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 35
Project: Mussy-Robot   Author: arnomoonens   File: getLandmark.py    MIT License 5 votes vote down vote up
def get_landmarks(image):
    detections = detector(image, 1)
    for k,d in enumerate(detections): #For all detected face instances individually
        shape = predictor(image,d) #Draw Facial Landmarks with the predictor class
        xlist = []
        ylist = []
        for i in range(1,68): #Store X and Y coordinates in two lists
            xlist.append(float(shape.part(i).x))
            ylist.append(float(shape.part(i).y))
            
        xmean = np.mean(xlist) #Get the mean of both axes to determine centre of gravity
        ymean = np.mean(ylist)
        xcentral = [(x-xmean) for x in xlist] #get distance between each point and the central point in both axes
        ycentral = [(y-ymean) for y in ylist]

        if xlist[26] == xlist[29]: #If x-coordinates of the set are the same, the angle is 0, catch to prevent 'divide by 0' error in function
            anglenose = 0
        else:
            anglenose = int(math.atan((ylist[26]-ylist[29])/(xlist[26]-xlist[29]))*180/math.pi)

        if anglenose < 0:
            anglenose += 90
        else:
            anglenose -= 90

        landmarks_vectorised = []
        for x, y, w, z in zip(xcentral, ycentral, xlist, ylist):
            landmarks_vectorised.append(x)
            landmarks_vectorised.append(y)
            meannp = np.asarray((ymean,xmean))
            coornp = np.asarray((z,w))
            dist = np.linalg.norm(coornp-meannp)
            anglerelative = (math.atan((z-ymean)/(w-xmean))*180/math.pi) - anglenose
            landmarks_vectorised.append(dist)
            landmarks_vectorised.append(anglerelative)

    if len(detections) < 1: 
        landmarks_vectorised = "error"
    return landmarks_vectorised 
Example 36
Project: PiClock   Author: n0bel   File: GoogleMercatorProjection.py    MIT License 5 votes vote down vote up
def fromPointToLatLng(self, point):
        origin = self.pixelOrigin_
        lng = (point.x - origin.x) / self.pixelsPerLonDegree_
        latRadians = (point.y - origin.y) / -self.pixelsPerLonRadian_
        lat = radiansToDegrees(2.0 * math.atan(math.exp(latRadians)) -
                               math.pi / 2.0)
        return LatLng(lat, lng) 
Example 37
Project: NiujiaoDebugger   Author: MrSrc   File: test_math.py    GNU General Public License v3.0 5 votes vote down vote up
def testAtan(self):
        self.assertRaises(TypeError, math.atan)
        self.ftest('atan(-1)', math.atan(-1), -math.pi/4)
        self.ftest('atan(0)', math.atan(0), 0)
        self.ftest('atan(1)', math.atan(1), math.pi/4)
        self.ftest('atan(inf)', math.atan(INF), math.pi/2)
        self.ftest('atan(-inf)', math.atan(NINF), -math.pi/2)
        self.assertTrue(math.isnan(math.atan(NAN))) 
Example 38
Project: NiujiaoDebugger   Author: MrSrc   File: test_math.py    GNU General Public License v3.0 5 votes vote down vote up
def testAtanh(self):
        self.assertRaises(TypeError, math.atan)
        self.ftest('atanh(0)', math.atanh(0), 0)
        self.ftest('atanh(0.5)', math.atanh(0.5), 0.54930614433405489)
        self.ftest('atanh(-0.5)', math.atanh(-0.5), -0.54930614433405489)
        self.assertRaises(ValueError, math.atanh, 1)
        self.assertRaises(ValueError, math.atanh, -1)
        self.assertRaises(ValueError, math.atanh, INF)
        self.assertRaises(ValueError, math.atanh, NINF)
        self.assertTrue(math.isnan(math.atanh(NAN))) 
Example 39
Project: Autoenv   Author: intelligent-control-lab   File: VecSE2.py    MIT License 5 votes vote down vote up
def atan(self):
        return math.atan(self.y/self.x) 
Example 40
Project: Autoenv   Author: intelligent-control-lab   File: VecE2.py    MIT License 5 votes vote down vote up
def atan(self):
        if self.x == 0:
            if self.y > 0:
                return math.pi/2
            elif self.y < 0:
                return -math.pi/2
            else:
                return 0
        return math.atan(self.y/self.x) 
Example 41
Project: Traffic-Signs-and-Object-Detection   Author: dark-archerx   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def _pix_to_lat(k, latpix, ntiles, _TILESIZE, zoom):

    return math.degrees(math.pi/2 - 2 * math.atan(math.exp(((latpix + _pixels_to_degrees((k-ntiles/2)*_TILESIZE, zoom)) - _EARTHPIX) / _pixrad))) 
Example 42
Project: autorace2017-team-loading   Author: AuTURBO   File: lane_follower.py    Apache License 2.0 5 votes vote down vote up
def PIDcontrol(self, x0, y0, x1, y1, x2, y2):
        Ip = 0.2
        distance = 350
        if x1 != x2:
            a = (float(y2)-float(y1))/(float(x2)-float(x1))
        else:
            a = (float(y2)-float(y1))/1
        b = -1
        c = -a*x1 + y1
        theta_current = -math.atan(1/a)*180/np.pi
        sign_, err = distance_dot2line(a, b, c, x0, y0)
        theta_desired = (err - distance) * Ip * sign_
        theta_wheel = (theta_desired - theta_current) * 0.005 * self.speed # origin : 0.005 next : 0.007
        return sign_, theta_wheel 
Example 43
Project: Gesture-Research   Author: s9k96   File: LedByGesture_Rpi.py    MIT License 5 votes vote down vote up
def angle(x,y):
	if x == 0: return None
	return math.fabs(math.degrees(math.atan(y/float(x)))) 
Example 44
Project: GISServer_code   Author: crynetsystems   File: arcgisdownloader.py    GNU General Public License v3.0 5 votes vote down vote up
def num2deg(xtile, ytile, zoom):
    n = 2.0 ** zoom
    lon_deg = xtile / n * 360.0 - 180.0
    lat_rad = math.atan(math.sinh(math.pi * (1 - 2 * ytile / n)))
    lat_deg = math.degrees(lat_rad)
    return (lat_deg, lon_deg) 
Example 45
Project: PyR2   Author: caelan   File: genericRobot.py    MIT License 5 votes vote down vote up
def mapFromTan(z, limits):
    (tlo, thi) = limits
    return ((thi - tlo)/math.pi)*math.atan(z) + ((thi + tlo)/2.) 
Example 46
Project: ems   Author: mtils   File: geotiledmapdata.py    MIT License 5 votes vote down vote up
def _worldReferencePositionToCoordinate(self, pixel):
        '''
        Converts the pixel position \a pixel on the map to a coordinate.

        The pixel position is relative the entire map at the maximum zoom level.
    
        The default implementation is based on the Mercator projection.
        
        
        @param pixel: The pixel on screen
        @type pixel: QPoint
        '''
        fx = float(pixel.x()) / float(self._worldReferenceSize.width())
        fy = float(pixel.y()) / float(self._worldReferenceSize.height())
        
        if fy < 0.0:
            fy = 0.0
        elif fy > 1.0:
            fy = 1.0
        
        if fy == 0.0:
            lat = 90.0
        elif fy == 1.0:
            lat = -90.0
        else:
            lat = ((180.0 / math.pi) * (2.0 * math.atan(math.exp(math.pi * (1.0 - 2.0 * fy))) - (math.pi / 2.0)))
        
        if fx >= 0:
            lng = rmod(fx, 1.0)
        else:
            lng = rmod(1.0 - rmod(-1.0 * fx, 1.0), 1.0)
            
        #lng = fx
    
        lng = lng * 360.0 - 180.0
        
        return GeoCoordinate(lat, lng, 0.0) 
Example 47
Project: cct   Author: awacha   File: pinholeconfiguration.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def qmin(self) -> float:
        return (4 * math.pi * math.sin(0.5 * math.atan(self.tantthmin)) /
                self.wavelength) 
Example 48
Project: cct   Author: awacha   File: pinholeconfiguration.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def qmin(self) -> float:
        return (4 * math.pi * math.sin(0.5 * math.atan(self.tantthmin)) /
                self.wavelength) 
Example 49
Project: pyh3   Author: buzzfeed   File: h3math.py    MIT License 5 votes vote down vote up
def compute_delta_theta(r, rp, phi):
    return math.atan(math.tanh(r / K) /
                     (math.sinh(rp / K) * math.sinh(phi))) 
Example 50
Project: pyh3   Author: buzzfeed   File: h3math.py    MIT License 5 votes vote down vote up
def compute_delta_phi(r, rp):
    return math.atan(math.tanh(r / K) / math.sinh(rp / K)) 
Example 51
Project: maps_stitcher   Author: haochi   File: geo.py    GNU General Public License v2.0 5 votes vote down vote up
def fromPointToLatLng(self, point):
        lat = ( 2 * math.atan(math.exp((point.y - self.MID_POINT.y) / - ( self.PIXELS / (2 * math.pi)))) - math.pi / 2) /(math.pi/(self.DEGREES_IN_CIRCLE/2))
        lng = (point.x - self.MID_POINT.x) / self.PIXELS_PER_DEGREE
        return LatLng(lat, lng) 
Example 52
Project: TransferbilityFromAttributionMaps   Author: zju-vipa   File: task_viz.py    MIT License 5 votes vote down vote up
def check_if_point_in_fustrum( point, fov ):
    return all( [np.abs( math.atan( coord / point[2] ) ) < fov/2. for coord in point[:2]] ) 
Example 53
Project: geodata   Author: microelly2   File: transversmercator.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def fromGeographic(self, lat, lon):
        lat = math.radians(lat)
        lon = math.radians(lon-self.lon)
        B = math.sin(lon) * math.cos(lat)
        x = 0.5 * self.k * self.radius * math.log((1+B)/(1-B))
        y = self.k * self.radius * ( math.atan(math.tan(lat)/math.cos(lon)) - self.latInRadians )
        return (x,y) 
Example 54
Project: geodata   Author: microelly2   File: transversmercator.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def toGeographic(self, x, y):
        x = x/(self.k * self.radius)
        y = y/(self.k * self.radius)
        D = y + self.latInRadians
        lon = math.atan(math.sinh(x)/math.cos(D))
        lat = math.asin(math.sin(D)/math.cosh(x))

        lon = self.lon + math.degrees(lon)
        lat = math.degrees(lat)
        return (lat, lon) 
Example 55
Project: asciimatics   Author: peterbrittain   File: maps.py    Apache License 2.0 5 votes vote down vote up
def _inc_lat(self, latitude, delta):
        """Shift the latitude by the required number of pixels (i.e. text lines)."""
        y = self._convert_latitude(latitude)
        y += delta
        return 360 / pi * atan(
            exp((180 - y * 360 / (2 ** self._zoom) / self._size) * pi / 180)) - 90 
Example 56
Project: PokemonGo-Bot   Author: PokemonGoF   File: utils.py    MIT License 5 votes vote down vote up
def y2lat(y):
    ts = exp(-y / EARTH_RADIUS_MAJ)
    phi = pi / 2.0 - 2 * atan(ts)
    dphi = 1.0
    for i in range(15):
        if abs(dphi) < 0.000000001:
            break
        con = ECCENT * sin(phi)
        dphi = pi / 2.0 - 2 * atan (ts * pow((1.0 - con) / (1.0 + con), COM)) - phi
        phi += dphi
    return rad2deg(phi) 
Example 57
Project: qgis-xyz-tiles   Author: lutraconsulting   File: tiles_xyz_algorithm.py    GNU General Public License v2.0 5 votes vote down vote up
def num2deg(xtile, ytile, zoom):
    n = 2.0 ** zoom
    lon_deg = xtile / n * 360.0 - 180.0
    lat_rad = math.atan(math.sinh(math.pi * (1 - 2 * ytile / n)))
    lat_deg = math.degrees(lat_rad)
    return (lat_deg, lon_deg) 
Example 58
Project: Geognomo   Author: ZYenGroupLimited   File: geocode_encoder.py    MIT License 5 votes vote down vote up
def icosahedron(self):
        latitude = self.latitude
        longitude = self.longitude
        # Top Pyramid
        if latitude >= math.atan(0.5):
            icosahedron = int(5 * longitude / (2 * math.pi)) + 1
        # Bottom Pyramid - offset angle with Top Pyramid is math.pi/5
        elif latitude <= math.atan(-0.5):
            icosahedron = int(5 * (longitude - math.pi / 5) / (2 * math.pi)) + 16
            if icosahedron == 15:
                icosahedron = 20
        # Middle Band
        else:
            # Initial Middle Band Division
            topPyramidAbove = int(5 * longitude / (2 * math.pi))
            a = numpy.matrix([[topPyramidAbove * 2 * math.pi / 5, 1],
                              [topPyramidAbove * 2 * math.pi / 5 + math.pi / 5, 1]])
            b = numpy.array([math.atan(0.5), math.atan(-0.5)])
            leftEdges = numpy.linalg.solve(a, b)
            c = numpy.matrix([[((topPyramidAbove + 1)) * 2 * math.pi / 5, 1],
                              [topPyramidAbove * 2 * math.pi / 5 + math.pi / 5, 1]])
            d = numpy.array([math.atan(0.5), math.atan(-0.5)])
            rightEdges = numpy.linalg.solve(c, d)
            if latitude < leftEdges[0] * longitude + leftEdges[1]:
                if topPyramidAbove == 0:
                    icosahedron = 15
                else:
                    icosahedron = topPyramidAbove + 10
            if latitude >= leftEdges[0] * longitude + leftEdges[1] and latitude > rightEdges[0] * longitude \
                    + rightEdges[1]:
                icosahedron = topPyramidAbove + 6
            if latitude <= rightEdges[0] * longitude + rightEdges[1]:
                icosahedron = topPyramidAbove + 11
        return icosahedron 
Example 59
Project: Geognomo   Author: ZYenGroupLimited   File: geocode_encoder.py    MIT License 5 votes vote down vote up
def covertToXY(self):
        latitude = self.latitude
        longitude = self.longitude
        level = self.level
        icosahedron = self.icosahedron()
        # move the left corner to (0,0)
        if icosahedron <= 5:
            longitude = longitude - ((icosahedron - 1) * 2 * math.pi / 5)
            latitude = latitude - math.atan(0.5)
        elif icosahedron > 5 and icosahedron <= 10:
            longitude = longitude - ((icosahedron - 6) * 2 * math.pi / 5)
            latitude = math.atan(0.5) - latitude
        elif icosahedron > 10 and icosahedron <= 15:
            longitude = longitude - math.pi / 5 - ((icosahedron - 11) * 2 * math.pi / 5)
            latitude = latitude + math.atan(0.5)
            if longitude < 0:
                longitude = longitude + 2 * math.pi
        else:
            longitude = longitude - math.pi / 5 - ((icosahedron - 16) * 2 * math.pi / 5)
            latitude = -latitude - math.atan(0.5)
            if longitude < 0:
                longitude = longitude + 2 * math.pi
        # Top & Bottom Pyramid
        if icosahedron <= 5 or icosahedron >= 16:
            r = latitude / (math.pi / 2 - math.atan(0.5))
            pointX = 2 ** (level - 1) * (r + 5 * longitude * (1 - r) / math.pi)
            pointY = 2 ** (level - 1) * math.sqrt(3) * r
        # Middle Band
        else:
            pointX = (5 * 2 ** (level - 1) * longitude) / math.pi
            pointY = (2 ** (level - 2) * math.sqrt(3) * latitude) / math.atan(0.5)
        pointXY = (pointX, pointY)
        c = "lat: " + str(self.latitude) + ", lon:" + str(self.longitude) + ", x:" + str(pointX) + ", y:" + str(pointY)
        return pointXY 
Example 60
Project: linien   Author: hermitdemschoenenleben   File: cordic.py    GNU General Public License v3.0 5 votes vote down vote up
def _constants(self, stages, bits):
        if self.func_mode == "circular":
            s = range(stages)
            a = [atan(2**-i) for i in s]
            g = [sqrt(1 + 2**(-2*i)) for i in s]
            #zmax = sum(a)
            # use pi anyway as the input z can cause overflow
            # and we need the range for quadrant mapping
            zmax = pi
        elif self.func_mode == "linear":
            s = range(stages)
            a = [2**-i for i in s]
            g = [1 for i in s]
            #zmax = sum(a)
            # use 2 anyway as this simplifies a and scaling
            zmax = 2.
        else:  # hyperbolic
            s = []
            # need to repeat some stages:
            j = 4
            for i in range(stages):
                if i == j:
                    s.append(j)
                    j = 3*j + 1
                s.append(i + 1)
            a = [atanh(2**-i) for i in s]
            g = [sqrt(1 - 2**(-2*i)) for i in s]
            zmax = sum(a)*2
        # round here helps the width=2**i - 1 case but hurts the
        # important width=2**i case
        cast = int
        if log(bits)/log(2) % 1:
            cast = round
        a = [cast(ai*2**(bits - 1)/zmax) for ai in a]
        gain = 1.
        for gi in g:
            gain *= gi
        return a, s, zmax, gain 
Example 61
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 5 votes vote down vote up
def pixelstolatlon(px, py, zoom):
    res = INITIAL_RESOLUTION / (2**zoom)
    mx = px * res - ORIGIN_SHIFT
    my = py * res - ORIGIN_SHIFT
    lat = (my / ORIGIN_SHIFT) * 180.0
    lat = 180 / pi * (2*atan(exp(lat*pi/180.0)) - pi/2.0)
    lon = (mx / ORIGIN_SHIFT) * 180.0
    return lat, lon

############################################

# a neighbourhood in Lajeado, Brazil: 
Example 62
Project: open3words   Author: sirmmo   File: convert.py    MIT License 5 votes vote down vote up
def num2deg(xtile, ytile, zoom):
  n = 2.0 ** zoom
  lon_deg = xtile / n * 360.0 - 180.0
  lat_rad = math.atan(math.sinh(math.pi * (1 - 2 * ytile / n)))
  lat_deg = math.degrees(lat_rad)
  return (lat_deg, lon_deg) 
Example 63
Project: fastchess   Author: thomasahle   File: fastchess.py    GNU General Public License v3.0 5 votes vote down vote up
def cp_to_win(cp):
    return math.atan(cp / 100) * 2 / math.pi 
Example 64
Project: pix2pix_map_tiles   Author: NARO-41605   File: DataSetMake_tfwiter.py    MIT License 5 votes vote down vote up
def tile2latlon(x, y, z):
    lon = (x / 2.0**z) * 360 - 180 # 経度(東経)
    mapy = (y / 2.0**z) * 2 * math.pi - math.pi
    lat = 2 * math.atan(math.e ** (- mapy)) * 180 / math.pi - 90 # 緯度(北緯)
    return [lon,lat] 
Example 65
Project: pix2pix_map_tiles   Author: NARO-41605   File: DataSetMake_tfwiter_result.py    MIT License 5 votes vote down vote up
def tile2latlon(x, y, z):
    lon = (x / 2.0**z) * 360 - 180 # 経度(東経)
    mapy = (y / 2.0**z) * 2 * math.pi - math.pi
    lat = 2 * math.atan(math.e ** (- mapy)) * 180 / math.pi - 90 # 緯度(北緯)
    return [lon,lat] 
Example 66
Project: Perspective   Author: TypesettingTools   File: perspective.py    MIT License 4 votes vote down vote up
def unrot(coord_in, org, diag=True, get_rot=False):
    screen_z = 312.5
    shift = org.mul(-1)
    coord = [c.add(shift) for c in coord_in]
    center = intersect(coord[0::2], coord[1::2])
    center = Point(center.x, center.y, screen_z)
    rays = [Point(c.x, c.y, screen_z) for c in coord]
    f = []
    for i in range(2):
        vp1 = vec_pr(rays[0+i], center).length()
        vp2 = vec_pr(rays[2+i], center).length()
        a = rays[0+i]
        c = rays[2+i].mul(vp1/vp2)
        m = a.add(c).mul(0.5)
        r = center.z/m.z;
        a = a.mul(r)
        c = c.mul(r)
        f.append((a, c))
    (a, c), (b, d) = f[0], f[1]
    ratio = abs(dist(a, b)/dist(a, d))
    diag_diff = ((dist(a, c)-dist(b, d)))/(dist(a, c)+dist(b, d))
    n = vec_pr(vector(a, b), vector(a, c))
    n0 = vec_pr(vector(rays[0], rays[1]), vector(rays[0], rays[2]))
    flip = 1 if sc_pr(n, n0)>0 else -1
    if not get_rot:
        return diag_diff if diag else ratio#*flip
    if flip<0:
        return None
    fry = math.atan(n.x/n.z)
    s = ""
    s+= "\\fry%.2f" % (-fry/math.pi*180)
    rot_n = n.rot_y(fry)
    frx = -math.atan(rot_n.y/rot_n.z)
    if n0.z < 0:
        frx += math.pi
    s+= "\\frx%.2f" % (-frx/math.pi*180)
    n = vector(a, b)
    ab_unrot = vector(a, b).rot_y(fry).rot_x(frx)
    ac_unrot = vector(a, c).rot_y(fry).rot_x(frx)
    ad_unrot = vector(a, d).rot_y(fry).rot_x(frx)
    frz = math.atan2(ab_unrot.y, ab_unrot.x)
    s += "\\frz%.2f" % (-frz/math.pi*180)
    ad_unrot = ad_unrot.rot_z(frz)
    fax = ad_unrot.x/ad_unrot.y
    if abs(fax)>0.01:
        s += "\\fax%.2f" % (fax)
    return s 
Example 67
Project: iceaddr   Author: sveinbjornt   File: add_placename_data.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def isnet93_to_wgs84(xx, yy):
    x = xx
    y = yy
    a = 6378137.0
    f = 1 / 298.257222101
    lat1 = 64.25
    lat2 = 65.75
    latc = 65.00
    lonc = 19.00
    eps = 0.00000000001

    def fx(p):
        return a * math.cos(p / rho) / math.sqrt(1 - math.pow(e * math.sin(p / rho), 2))

    def f1(p):
        return math.log((1 - p) / (1 + p))

    def f2(p):
        return f1(p) - e * f1(e * p)

    def f3(p):
        return pol1 * math.exp((f2(math.sin(p / rho)) - f2sin1) * sint / 2)

    rho = 45 / math.atan2(1.0, 1.0)
    e = math.sqrt(f * (2 - f))
    dum = f2(math.sin(lat1 / rho)) - f2(math.sin(lat2 / rho))
    sint = 2 * (math.log(fx(lat1)) - math.log(fx(lat2))) / dum
    f2sin1 = f2(math.sin(lat1 / rho))
    pol1 = fx(lat1) / sint
    polc = f3(latc) + 500000.0
    peq = (
        a
        * math.cos(latc / rho)
        / (sint * math.exp(sint * math.log((45 - latc / 2) / rho)))
    )
    pol = math.sqrt(math.pow(x - 500000, 2) + math.pow(polc - y, 2))
    lat = 90 - 2 * rho * math.atan(math.exp(math.log(pol / peq) / sint))
    lon = 0
    fact = rho * math.cos(lat / rho) / sint / pol
    fact = rho * math.cos(lat / rho) / sint / pol
    delta = 1.0
    while math.fabs(delta) > eps:
        delta = (f3(lat) - pol) * fact
        lat += delta
    lon = -(lonc + rho * math.atan((500000 - x) / (polc - y)) / sint)

    return {"lat": round(lat, 7), "lng": round(lon, 7)} 
Example 68
Project: kivy-smoothie-host   Author: wolfmanjm   File: mpg_knob.py    GNU General Public License v3.0 4 votes vote down vote up
def update_angle(self, touch, first= False):
        posx, posy          =   touch.pos
        cx, cy              =   self.center
        rx, ry              =   posx - cx, posy - cy

        if ry >= 0:                                 # Quadrants are clockwise.
            quadrant = 1 if rx >= 0 else 4
        else:
            quadrant = 3 if rx <= 0 else 2

        try:
            angle    = math.atan(rx / ry) * (180./math.pi)
            if quadrant == 2 or quadrant == 3:
                angle = 180 + angle
            elif quadrant == 4:
                angle = 360 + angle

        except:                                   # atan not def for angle 90 and 270
            angle = 90 if quadrant <= 2 else 270

        # handle relative ticks per move
        if first:
            self._start_angle= angle
            self._last_angle= angle
            #print('start angle= {}'.format(self._start_angle))

        #print("angle= {}, direction= {}, clicks= {}".format(angle, self._last_angle <= angle, abs(self._last_angle-angle)))
        t= angle-self._last_angle
        # handle wrap around
        if t > 270:
            t= t - 360
        if t < -270:
            t= t + 360

        if abs(t) >= 1.0:
            # only issue event every full degree
            self.ticks= int(t)
            self._last_angle= angle
            self.dispatch('on_tick')

        # original handle absolute position
        self._angle_step    =   (self.step*360)/(self.max - self.min)
        self._angle         =   self._angle_step
        while self._angle < angle:
            self._angle     =   self._angle + self._angle_step

        relativeValue   =   pow((angle/360.), 1./self.curve)
        self.value      =   (relativeValue * (self.max - self.min)) + self.min 
Example 69
Project: fusion360-airfoil-generator   Author: arnaudin   File: fusion360-airfoil-generator-addin.py    MIT License 4 votes vote down vote up
def naca4(number, n, finite_TE = defaultAirfoilFT, half_cosine_spacing = defaultAirfoilHalfCosine):
    """
    Returns 2*n+1 points in [0 1] for the given 4 digit NACA number string
    """

    m = float(number[0])/100.0
    p = float(number[1])/10.0
    t = float(number[2:])/100.0

    a0 = +0.2969
    a1 = -0.1260
    a2 = -0.3516
    a3 = +0.2843

    if finite_TE:
        a4 = -0.1015 # For finite thick TE
    else:
        a4 = -0.1036 # For zero thick TE

    if half_cosine_spacing:
        beta = linspace(0.0,pi,n+1)
        x = [(0.5*(1.0-cos(xx))) for xx in beta]  # Half cosine based spacing
    else:
        x = linspace(0.0,1.0,n+1)

    yt = [5*t*(a0*sqrt(xx)+a1*xx+a2*pow(xx,2)+a3*pow(xx,3)+a4*pow(xx,4)) for xx in x]

    xc1 = [xx for xx in x if xx <= p]
    xc2 = [xx for xx in x if xx > p]

    if p == 0:
        xu = x
        yu = yt

        xl = x
        yl = [-xx for xx in yt]

        xc = xc1 + xc2
        zc = [0]*len(xc)
    else:
        yc1 = [m/pow(p,2)*xx*(2*p-xx) for xx in xc1]
        yc2 = [m/pow(1-p,2)*(1-2*p+xx)*(1-xx) for xx in xc2]
        zc = yc1 + yc2

        dyc1_dx = [m/pow(p,2)*(2*p-2*xx) for xx in xc1]
        dyc2_dx = [m/pow(1-p,2)*(2*p-2*xx) for xx in xc2]
        dyc_dx = dyc1_dx + dyc2_dx

        theta = [atan(xx) for xx in dyc_dx]

        xu = [xx - yy * sin(zz) for xx,yy,zz in zip(x,yt,theta)]
        yu = [xx + yy * cos(zz) for xx,yy,zz in zip(zc,yt,theta)]

        xl = [xx + yy * sin(zz) for xx,yy,zz in zip(x,yt,theta)]
        yl = [xx - yy * cos(zz) for xx,yy,zz in zip(zc,yt,theta)]

    X = xu[::-1] + xl[1:]
    Z = yu[::-1] + yl[1:]

    return X,Z 
Example 70
Project: fusion360-airfoil-generator   Author: arnaudin   File: fusion360-airfoil-generator-script.py    MIT License 4 votes vote down vote up
def naca4(number, n, finite_TE = defaultAirfoilFT, half_cosine_spacing = defaultAirfoilHalfCosine):
    """
    Returns 2*n+1 points in [0 1] for the given 4 digit NACA number string
    """

    m = float(number[0])/100.0
    p = float(number[1])/10.0
    t = float(number[2:])/100.0

    a0 = +0.2969
    a1 = -0.1260
    a2 = -0.3516
    a3 = +0.2843

    if finite_TE:
        a4 = -0.1015 # For finite thick TE
    else:
        a4 = -0.1036 # For zero thick TE

    if half_cosine_spacing:
        beta = linspace(0.0,pi,n+1)
        x = [(0.5*(1.0-cos(xx))) for xx in beta]  # Half cosine based spacing
    else:
        x = linspace(0.0,1.0,n+1)

    yt = [5*t*(a0*sqrt(xx)+a1*xx+a2*pow(xx,2)+a3*pow(xx,3)+a4*pow(xx,4)) for xx in x]

    xc1 = [xx for xx in x if xx <= p]
    xc2 = [xx for xx in x if xx > p]

    if p == 0:
        xu = x
        yu = yt

        xl = x
        yl = [-xx for xx in yt]

        xc = xc1 + xc2
        zc = [0]*len(xc)
    else:
        yc1 = [m/pow(p,2)*xx*(2*p-xx) for xx in xc1]
        yc2 = [m/pow(1-p,2)*(1-2*p+xx)*(1-xx) for xx in xc2]
        zc = yc1 + yc2

        dyc1_dx = [m/pow(p,2)*(2*p-2*xx) for xx in xc1]
        dyc2_dx = [m/pow(1-p,2)*(2*p-2*xx) for xx in xc2]
        dyc_dx = dyc1_dx + dyc2_dx

        theta = [atan(xx) for xx in dyc_dx]

        xu = [xx - yy * sin(zz) for xx,yy,zz in zip(x,yt,theta)]
        yu = [xx + yy * cos(zz) for xx,yy,zz in zip(zc,yt,theta)]

        xl = [xx + yy * sin(zz) for xx,yy,zz in zip(x,yt,theta)]
        yl = [xx - yy * cos(zz) for xx,yy,zz in zip(zc,yt,theta)]

    X = xu[::-1] + xl[1:]
    Z = yu[::-1] + yl[1:]

    return X,Z 
Example 71
Project: esys-pbi   Author: fsxfreak   File: transformations.py    MIT License 4 votes vote down vote up
def shear_from_matrix(matrix):
    """Return shear angle, direction and plane from shear matrix.

    >>> 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))
    >>> S0 = shear_matrix(angle, direct, point, normal)
    >>> angle, direct, point, normal = shear_from_matrix(S0)
    >>> S1 = shear_matrix(angle, direct, point, normal)
    >>> is_same_transform(S0, S1)
    True

    """
    M = numpy.array(matrix, dtype=numpy.float64, copy=False)
    M33 = M[:3, :3]
    # normal: cross independent eigenvectors corresponding to the eigenvalue 1
    w, V = numpy.linalg.eig(M33)
    i = numpy.where(abs(numpy.real(w) - 1.0) < 1e-4)[0]
    if len(i) < 2:
        raise ValueError("no two linear independent eigenvectors found {}".format(w))
    V = numpy.real(V[:, i]).squeeze().T
    lenorm = -1.0
    for i0, i1 in ((0, 1), (0, 2), (1, 2)):
        n = numpy.cross(V[i0], V[i1])
        w = vector_norm(n)
        if w > lenorm:
            lenorm = w
            normal = n
    normal /= lenorm
    # direction and angle
    direction = numpy.dot(M33 - numpy.identity(3), normal)
    angle = vector_norm(direction)
    direction /= angle
    angle = math.atan(angle)
    # point: eigenvector corresponding to eigenvalue 1
    w, V = numpy.linalg.eig(M)
    i = numpy.where(abs(numpy.real(w) - 1.0) < 1e-8)[0]
    if not len(i):
        raise ValueError("no eigenvector corresponding to eigenvalue 1")
    point = numpy.real(V[:, i[-1]]).squeeze()
    point /= point[3]
    return angle, direction, point, normal 
Example 72
Project: sk1-wx   Author: sk1project   File: editor_ellipse.py    GNU General Public License v3.0 4 votes vote down vote up
def apply_moving(self, event, start=False, final=False):
        point = event.get_point()
        wpoint = self.canvas.point_win_to_doc(point)
        invtrafo = libgeom.invert_trafo(self.target.trafo)
        x, y = libgeom.apply_trafo_to_point(wpoint, invtrafo)
        x -= 0.5
        y -= 0.5
        angle = 0.0
        if x > 0 and y > 0:
            angle = math.atan(y / x)
        elif x == 0 and y > 0:
            angle = math.pi / 2.0
        elif x < 0 < y:
            angle = math.atan(-x / y) + math.pi / 2.0
        elif x < 0 and y == 0:
            angle = math.pi
        elif x < 0 and y < 0:
            angle = math.atan(y / x) + math.pi
        elif x == 0 and y < 0:
            angle = 1.5 * math.pi
        elif x > 0 > y:
            angle = math.atan(x / -y) + 1.5 * math.pi
        elif x > 0 and y == 0:
            angle = 0.0
        elif x == 0 and y == 0:
            return
        if event.is_ctrl():
            fixed_angle = math.pi * config.ellipse_fixed_angle / 180.0
            angle //= fixed_angle
            angle *= fixed_angle
        else:
            contra_point = self.start_point
            if start:
                contra_point = self.end_point
            if contra_point.is_pressed(point):
                angle = contra_point.get_angle()
        circle_type = self.orig_type
        if event.is_alt() and not circle_type == sk2const.ARC_ARC:
            circle_type = sk2const.ARC_CHORD
            if libgeom.distance([x, y]) < 0.5:
                circle_type = sk2const.ARC_PIE_SLICE
        angle1 = self.orig_angle1
        angle2 = self.orig_angle2
        if start:
            angle1 = angle
        else:
            angle2 = angle
        if final:
            self.api.set_circle_properties_final(circle_type, angle1, angle2,
                                                 self.orig_type,
                                                 self.orig_angle1,
                                                 self.orig_angle2, self.target)
        else:
            self.api.set_circle_properties(circle_type, angle1,
                                           angle2, self.target)
        self.update_points() 
Example 73
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 74
Project: RouteOptimization   Author: andre-le   File: geodesic.py    MIT License 4 votes vote down vote up
def __init__(self, a, f):
    """Construct a Geodesic object

    :param a: the equatorial radius of the ellipsoid in meters
    :param f: the flattening of the ellipsoid

    An exception is thrown if *a* or the polar semi-axis *b* = *a* (1 -
    *f*) is not a finite positive quantity.

    """

    self.a = float(a)
    """The equatorial radius in meters (readonly)"""
    self.f = float(f)
    """The flattening (readonly)"""
    self._f1 = 1 - self.f
    self._e2 = self.f * (2 - self.f)
    self._ep2 = self._e2 / Math.sq(self._f1) # e2 / (1 - e2)
    self._n = self.f / ( 2 - self.f)
    self._b = self.a * self._f1
    # authalic radius squared
    self._c2 = (Math.sq(self.a) + Math.sq(self._b) *
                (1 if self._e2 == 0 else
                 (Math.atanh(math.sqrt(self._e2)) if self._e2 > 0 else
                  math.atan(math.sqrt(-self._e2))) /
                 math.sqrt(abs(self._e2))))/2
    # The sig12 threshold for "really short".  Using the auxiliary sphere
    # solution with dnm computed at (bet1 + bet2) / 2, the relative error in
    # the azimuth consistency check is sig12^2 * abs(f) * min(1, 1-f/2) / 2.
    # (Error measured for 1/100 < b/a < 100 and abs(f) >= 1/1000.  For a given
    # f and sig12, the max error occurs for lines near the pole.  If the old
    # rule for computing dnm = (dn1 + dn2)/2 is used, then the error increases
    # by a factor of 2.)  Setting this equal to epsilon gives sig12 = etol2.
    # Here 0.1 is a safety factor (error decreased by 100) and max(0.001,
    # abs(f)) stops etol2 getting too large in the nearly spherical case.
    self._etol2 = 0.1 * Geodesic.tol2_ / math.sqrt( max(0.001, abs(self.f)) *
                                                    min(1.0, 1-self.f/2) / 2 )
    if not(Math.isfinite(self.a) and self.a > 0):
      raise ValueError("Equatorial radius is not positive")
    if not(Math.isfinite(self._b) and self._b > 0):
      raise ValueError("Polar semi-axis is not positive")
    self._A3x = list(range(Geodesic.nA3x_))
    self._C3x = list(range(Geodesic.nC3x_))
    self._C4x = list(range(Geodesic.nC4x_))
    self._A3coeff()
    self._C3coeff()
    self._C4coeff() 
Example 75
Project: vo_single_camera_sos   Author: ubuntuslave   File: transformations.py    GNU General Public License v3.0 4 votes vote down vote up
def shear_from_matrix(matrix):
    """Return shear angle, direction and plane from shear matrix.

    >>> 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))
    >>> S0 = shear_matrix(angle, direct, point, normal)
    >>> angle, direct, point, normal = shear_from_matrix(S0)
    >>> S1 = shear_matrix(angle, direct, point, normal)
    >>> is_same_transform(S0, S1)
    True

    """
    M = numpy.array(matrix, dtype = numpy.float64, copy = False)
    M33 = M[:3, :3]
    # normal: cross independent eigenvectors corresponding to the eigenvalue 1
    w, V = numpy.linalg.eig(M33)
    i = numpy.where(abs(numpy.real(w) - 1.0) < 1e-4)[0]
    if len(i) < 2:
        raise ValueError("no two linear independent eigenvectors found %s" % w)
    V = numpy.real(V[:, i]).squeeze().T
    lenorm = -1.0
    for i0, i1 in ((0, 1), (0, 2), (1, 2)):
        n = numpy.cross(V[i0], V[i1])
        w = vector_norm(n)
        if w > lenorm:
            lenorm = w
            normal = n
    normal /= lenorm
    # direction and angle
    direction = numpy.dot(M33 - numpy.identity(3), normal)
    angle = vector_norm(direction)
    direction /= angle
    angle = math.atan(angle)
    # point: eigenvector corresponding to eigenvalue 1
    w, V = numpy.linalg.eig(M)
    i = numpy.where(abs(numpy.real(w) - 1.0) < 1e-8)[0]
    if not len(i):
        raise ValueError("no eigenvector corresponding to eigenvalue 1")
    point = numpy.real(V[:, i[-1]]).squeeze()
    point /= point[3]
    return angle, direction, point, normal 
Example 76
Project: PyR2   Author: caelan   File: transformations.py    MIT License 4 votes vote down vote up
def shear_from_matrix(matrix):
    """Return shear angle, direction and plane from shear matrix.

    >>> 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))
    >>> S0 = shear_matrix(angle, direct, point, normal)
    >>> angle, direct, point, normal = shear_from_matrix(S0)
    >>> S1 = shear_matrix(angle, direct, point, normal)
    >>> is_same_transform(S0, S1)
    True

    """
    M = numpy.array(matrix, dtype=numpy.float64, copy=False)
    M33 = M[:3, :3]
    # normal: cross independent eigenvectors corresponding to the eigenvalue 1
    l, V = numpy.linalg.eig(M33)
    i = numpy.where(abs(numpy.real(l) - 1.0) < 1e-4)[0]
    if len(i) < 2:
        raise ValueError("No two linear independent eigenvectors found %s" % l)
    V = numpy.real(V[:, i]).squeeze().T
    lenorm = -1.0
    for i0, i1 in ((0, 1), (0, 2), (1, 2)):
        n = numpy.cross(V[i0], V[i1])
        l = vector_norm(n)
        if l > lenorm:
            lenorm = l
            normal = n
    normal /= lenorm
    # direction and angle
    direction = numpy.dot(M33 - numpy.identity(3), normal)
    angle = vector_norm(direction)
    direction /= angle
    angle = math.atan(angle)
    # point: eigenvector corresponding to eigenvalue 1
    l, V = numpy.linalg.eig(M)
    i = numpy.where(abs(numpy.real(l) - 1.0) < 1e-8)[0]
    if not len(i):
        raise ValueError("no eigenvector corresponding to eigenvalue 1")
    point = numpy.real(V[:, i[-1]]).squeeze()
    point /= point[3]
    return angle, direction, point, normal 
Example 77
Project: cozmo_driver   Author: OTL   File: transformations.py    Apache License 2.0 4 votes vote down vote up
def shear_from_matrix(matrix):
    """Return shear angle, direction and plane from shear matrix.

    >>> 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))
    >>> S0 = shear_matrix(angle, direct, point, normal)
    >>> angle, direct, point, normal = shear_from_matrix(S0)
    >>> S1 = shear_matrix(angle, direct, point, normal)
    >>> is_same_transform(S0, S1)
    True

    """
    M = numpy.array(matrix, dtype=numpy.float64, copy=False)
    M33 = M[:3, :3]
    # normal: cross independent eigenvectors corresponding to the eigenvalue 1
    l, V = numpy.linalg.eig(M33)
    i = numpy.where(abs(numpy.real(l) - 1.0) < 1e-4)[0]
    if len(i) < 2:
        raise ValueError("No two linear independent eigenvectors found %s" % l)
    V = numpy.real(V[:, i]).squeeze().T
    lenorm = -1.0
    for i0, i1 in ((0, 1), (0, 2), (1, 2)):
        n = numpy.cross(V[i0], V[i1])
        l = vector_norm(n)
        if l > lenorm:
            lenorm = l
            normal = n
    normal /= lenorm
    # direction and angle
    direction = numpy.dot(M33 - numpy.identity(3), normal)
    angle = vector_norm(direction)
    direction /= angle
    angle = math.atan(angle)
    # point: eigenvector corresponding to eigenvalue 1
    l, V = numpy.linalg.eig(M)
    i = numpy.where(abs(numpy.real(l) - 1.0) < 1e-8)[0]
    if not len(i):
        raise ValueError("no eigenvector corresponding to eigenvalue 1")
    point = numpy.real(V[:, i[-1]]).squeeze()
    point /= point[3]
    return angle, direction, point, normal 
Example 78
Project: Landsat8LST_SWA   Author: eduard-kazakov   File: modis_extent_generator.py    GNU General Public License v2.0 4 votes vote down vote up
def addVertexesToPolyPoints(polyPoints, vertexCount):
    """
    Add new vertexes to points list.
    :param polyPoints: list of points
    :param vertexCount: number of points to be added
    :return: new (extended) list of points
    """
    i = 0
    newPolyPoints = []
    while i < len(polyPoints) - 1:
        # first point
        newPolyPoints.append(QgsPoint(polyPoints[i][0], polyPoints[i][1]))

        dx = polyPoints[i + 1][0] - polyPoints[i][0]
        dy = polyPoints[i + 1][1] - polyPoints[i][1]
        length = math.sqrt(dx * dx + dy * dy)
        step = (length * 1.0) / (vertexCount * 1.0 - 1)
        if dx == 0 and dy == 0:
            i += 1
            continue

        if dx == 0.0:
            if dy > 0:
                a = 0
            else:
                a = math.pi
        elif dy == 0.0:
            if dx > 0:
                a = math.pi / 2
            else:
                a = (math.pi / 2) * 3
        else:
            r = math.atan(math.fabs(dx) / math.fabs(dy))

        if dx > 0:
            if dy > 0:
                a = r
            elif dy < 0:
                a = math.pi - r
        elif dx < 0:
            if dy > 0:
                a = 2 * math.pi - r
            elif dy < 0:
                a = math.pi + r
        j = 1
        while j < vertexCount:
            nX = polyPoints[i][0] + step * j * math.sin(a)
            nY = polyPoints[i][1] + step * j * math.cos(a)
            newPoint = QgsPoint(nX, nY)
            newPolyPoints.append(newPoint)
            j += 1
        # last point
        newPolyPoints.append(QgsPoint(polyPoints[i + 1][0], polyPoints[i + 1][1]))
        i += 1
    return newPolyPoints 
Example 79
Project: Geognomo   Author: ZYenGroupLimited   File: geocode_decoder.py    MIT License 4 votes vote down vote up
def covertToLatLon(QTMID, Px, Py):
    QTMCode = QTMID.split(",")[1]
    icos = int(QTMID.split(",")[0])
    k = len(QTMCode)

    if icos <= 5:
        LAT = (math.pi / 2 - math.atan(0.5)) * Py / (2 ** (k - 1) * math.sqrt(3))
        r = LAT / (math.pi / 2 - math.atan(0.5))
        if Py != math.sqrt(3) * 2 ** (k - 1):
            LON = ((Px / 2 ** (k - 1)) - r) * math.pi / ((1 - r) * 5)
        else:
            LON = 0
        LAT = LAT + math.atan(0.5)
        LON = LON + ((icos - 1) * 2 * math.pi / 5)

    elif icos > 5 and icos <= 10:
        LAT = Py * 2 * math.atan(0.5) / (2 ** (k - 1) * math.sqrt(3))
        LAT = math.atan(0.5) - LAT
        LON = Px * 2 * math.pi / (5 * 2 ** k)
        LON = LON + ((icos - 6) * 2 * math.pi / 5)

    elif icos > 10 and icos <= 15:
        LAT = Py * 2 * math.atan(0.5) / (2 ** (k - 1) * math.sqrt(3))
        LAT = LAT + math.atan(-0.5)
        LON = Px * 2 * math.pi / (5 * 2 ** k)
        LON = LON + math.pi / 5 + ((icos - 11) * 2 * math.pi / 5)
        if LON > 2 * math.pi:
            LON = LON - 2 * math.pi
    else:
        LAT = (math.pi / 2 - math.atan(0.5)) * Py / (2 ** (k - 1) * math.sqrt(3))
        r = LAT / (math.pi / 2 - math.atan(0.5))
        if Py != math.sqrt(3) * 2 ** (k - 1):
            LON = ((Px / 2 ** (k - 1)) - r) * math.pi / ((1 - r) * 5)
        else:
            LON = 0

        LAT = -LAT + math.atan(-0.5)
        LON = LON + math.pi / 5 + ((icos - 16) * 2 * math.pi / 5)
        if LON > 2 * math.pi:
            LON = LON - 2 * math.pi

    lat = round(LAT * 180 / math.pi, 6)
    lon = round(LON * 180 / math.pi, 6)
    if lon > 180:
        lon = lon - 360
        lon = round(lon, 6)

    if (lat <= -90 or lat >= 90) and (lon <= -180 or lon > 180):
        return str(("N/A", "N/A"))
    else:
        return str((lat, lon)) 
Example 80
Project: bop_toolkit   Author: thodan   File: transform.py    MIT License 4 votes vote down vote up
def shear_from_matrix(matrix):
  """Return shear angle, direction and plane from shear matrix.

  >>> 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))
  >>> S0 = shear_matrix(angle, direct, point, normal)
  >>> angle, direct, point, normal = shear_from_matrix(S0)
  >>> S1 = shear_matrix(angle, direct, point, normal)
  >>> is_same_transform(S0, S1)
  True

  """
  M = numpy.array(matrix, dtype=numpy.float64, copy=False)
  M33 = M[:3, :3]
  # normal: cross independent eigenvectors corresponding to the eigenvalue 1
  w, V = numpy.linalg.eig(M33)
  i = numpy.where(abs(numpy.real(w) - 1.0) < 1e-4)[0]
  if len(i) < 2:
    raise ValueError("no two linear independent eigenvectors found %s" % w)
  V = numpy.real(V[:, i]).squeeze().T
  lenorm = -1.0
  for i0, i1 in ((0, 1), (0, 2), (1, 2)):
    n = numpy.cross(V[i0], V[i1])
    w = vector_norm(n)
    if w > lenorm:
      lenorm = w
      normal = n
  normal /= lenorm
  # direction and angle
  direction = numpy.dot(M33 - numpy.identity(3), normal)
  angle = vector_norm(direction)
  direction /= angle
  angle = math.atan(angle)
  # point: eigenvector corresponding to eigenvalue 1
  w, V = numpy.linalg.eig(M)
  i = numpy.where(abs(numpy.real(w) - 1.0) < 1e-8)[0]
  if not len(i):
    raise ValueError("no eigenvector corresponding to eigenvalue 1")
  point = numpy.real(V[:, i[-1]]).squeeze()
  point /= point[3]
  return angle, direction, point, normal