Python math.acos() Examples

The following are 30 code examples for showing how to use math.acos(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module math , or try the search function .

Example 1
Project: dogTorch   Author: ehsanik   File: metrics.py    License: MIT License 6 votes vote down vote up
def get_angle_diff(self, target, result):
        size = target.size()
        sequence_length = size[1]
        all_averages = np.zeros((sequence_length)).astype(np.float)
        for seq_id in range(sequence_length):
            average = AverageMeter()
            for batch_id in range(size[0]):
                for imu_id in range(size[2]):
                    goal = Quaternion(target[batch_id, seq_id, imu_id])
                    out = Quaternion(result[batch_id, seq_id, imu_id])
                    acos = (2 * (np.dot(out.normalised.q, goal.normalised.q)**2)
                            - 1)
                    acos = round(acos, 6)
                    if acos > 1 or acos < -1:
                        pdb.set_trace()
                    radian = math.acos(acos)
                    average.update(radian)

            all_averages[seq_id] = (average.avg)

        return all_averages 
Example 2
Project: Localization   Author: kamalshadi   File: geometry.py    License: MIT License 6 votes vote down vote up
def c2s(self):
        R = self.dist(point(0, 0, 0))
        lg = math.atan(self.y / self.x)
        lat = acos(self.z / R)
        return (lg, lat, R)

    # ~ def transform(self,p1,p2):
    # ~ if isinstance(p2,point):
    # ~ v=vec(p1,p2)
    # ~ rot=v.angle()
    # ~ return self.transform(p1,rot)
    # ~ else:
    # ~ temp=self-p1
    # ~ rot=p2
    # ~ px=math.cos(rot)*temp.x+math.sin(rot)*temp.y
    # ~ py=-math.sin(rot)*temp.x+math.cos(rot)*temp.y
    # ~ return point(px,py) 
Example 3
Project: Localization   Author: kamalshadi   File: geometry.py    License: MIT License 6 votes vote down vote up
def map(self, p, inv=False):
        # cartesian to lat/lon
        # if inv is true lat/lon to cartesian
        R = self.R
        if not inv:
            ed = R * (vec(p - self.c).norm())
            ed = point(ed.dx, ed.dy, ed.dz)
            lon = math.atan2(ed.y, ed.x)
            lat1 = math.acos(abs(ed.z) / R)
            if ed.z > 0:
                lat = math.pi / 2 - lat1
            else:
                lat = -(math.pi / 2 - lat1)
            return point(lon, lat) * 180 / math.pi
        if inv:
            p = p * math.pi / 180
            z = R * math.sin(p.y)
            y = R * math.cos(p.y) * math.sin(p.x)
            x = R * math.cos(p.y) * math.cos(p.x)
            return point(x, y, z) 
Example 4
Project: honeybee   Author: ladybug-tools   File: gendaylit.py    License: GNU General Public License v3.0 6 votes vote down vote up
def theta_phi_to_dzeta_gamma(theta, phi, z):
    """Calculation of the angles dzeta and gamma."""
    dzeta = theta

    if ((math.cos(z) * math.cos(theta) + math.sin(z) * math.sin(theta) *
         math.cos(phi)) > 1 and (math.cos(z) * math.cos(theta) + math.sin(z) *
                                 math.sin(theta) * math.cos(phi) < 1.1)):
        gamma = 0
    elif math.cos(z) * math.cos(theta) + math.sin(z) * math.sin(theta) * \
            math.cos(phi) > 1.1:
        raise ValueError("error in calculation of gamma (angle between point and sun)")
    else:
        gamma = math.acos(math.cos(z) * math.cos(theta) + math.sin(z) *
                          math.sin(theta) * math.cos(phi))

    return dzeta, gamma 
Example 5
Project: NURBS-Python   Author: orbingol   File: linalg.py    License: MIT License 6 votes vote down vote up
def vector_angle_between(vector1, vector2, **kwargs):
    """ Computes the angle between the two input vectors.

    If the keyword argument ``degrees`` is set to *True*, then the angle will be in degrees. Otherwise, it will be
    in radians. By default, ``degrees`` is set to *True*.

    :param vector1: vector
    :type vector1: list, tuple
    :param vector2: vector
    :type vector2: list, tuple
    :return: angle between the vectors
    :rtype: float
    """
    degrees = kwargs.get('degrees', True)
    magn1 = vector_magnitude(vector1)
    magn2 = vector_magnitude(vector2)
    acos_val = vector_dot(vector1, vector2) / (magn1 * magn2)
    angle_radians = math.acos(acos_val)
    if degrees:
        return math.degrees(angle_radians)
    else:
        return angle_radians 
Example 6
Project: PyETo   Author: woodcrafty   File: fao.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def sunset_hour_angle(latitude, sol_dec):
    """
    Calculate sunset hour angle (*Ws*) from latitude and solar
    declination.

    Based on FAO equation 25 in Allen et al (1998).

    :param latitude: Latitude [radians]. Note: *latitude* should be negative
        if it in the southern hemisphere, positive if in the northern
        hemisphere.
    :param sol_dec: Solar declination [radians]. Can be calculated using
        ``sol_dec()``.
    :return: Sunset hour angle [radians].
    :rtype: float
    """
    _check_latitude_rad(latitude)
    _check_sol_dec_rad(sol_dec)

    cos_sha = -math.tan(latitude) * math.tan(sol_dec)
    # If tmp is >= 1 there is no sunset, i.e. 24 hours of daylight
    # If tmp is <= 1 there is no sunrise, i.e. 24 hours of darkness
    # See http://www.itacanet.org/the-sun-as-a-source-of-energy/
    # part-3-calculating-solar-angles/
    # Domain of acos is -1 <= x <= 1 radians (this is not mentioned in FAO-56!)
    return math.acos(min(max(cos_sha, -1.0), 1.0)) 
Example 7
Project: bop_toolkit   Author: thodan   File: pose_error.py    License: MIT License 6 votes vote down vote up
def re(R_est, R_gt):
  """Rotational Error.

  :param R_est: 3x3 ndarray with the estimated rotation matrix.
  :param R_gt: 3x3 ndarray with the ground-truth rotation matrix.
  :return: The calculated error.
  """
  assert (R_est.shape == R_gt.shape == (3, 3))
  error_cos = float(0.5 * (np.trace(R_est.dot(np.linalg.inv(R_gt))) - 1.0))

  # Avoid invalid values due to numerical errors.
  error_cos = min(1.0, max(-1.0, error_cos))

  error = math.acos(error_cos)
  error = 180.0 * error / np.pi  # Convert [rad] to [deg].
  return error 
Example 8
Project: pyth   Author: isaacg1   File: macros.py    License: MIT License 6 votes vote down vote up
def trig(a, b=' '):
    if is_num(a) and isinstance(b, int):

        funcs = [math.sin, math.cos, math.tan,
                 math.asin, math.acos, math.atan,
                 math.degrees, math.radians,
                 math.sinh, math.cosh, math.tanh,
                 math.asinh, math.acosh, math.atanh]

        return funcs[b](a)

    if is_lst(a):
        width = max(len(row) for row in a)
        padded_matrix = [list(row) + (width - len(row)) * [b] for row in a]
        transpose = list(zip(*padded_matrix))
        if all(isinstance(row, str) for row in a) and isinstance(b, str):
            normalizer = ''.join
        else:
            normalizer = list
        norm_trans = [normalizer(padded_row) for padded_row in transpose]
        return norm_trans
    return unknown_types(trig, ".t", a, b) 
Example 9
Project: miRge   Author: mhalushka   File: vector.py    License: GNU General Public License v3.0 6 votes vote down vote up
def spherical_cartesian_to_polar(vec):
    '''
    Return a parameterization of a vector of 3 coordinates:

    x = r sin u cos v
    y = r sin u sin v
    z = r cos u

    0 <= u <= pi
    -pi <= v <= pi

    Where u is the polar angle and v is the azimuth angle.

    @param vec: A vector of 3 cartesian coordinates.
    @return: (r, u, v)
    '''
    r = magnitude(vec)
    u = m.acos(vec[2] / r)
    v = m.atan2(vec[1], vec[0])

    nt.assert_allclose(vec[0], r * m.sin(u) * m.cos(v), rtol=1e-7, atol=1e-7)
    return (r, u, v) 
Example 10
Project: Python-world-gen   Author: brianbeauregard   File: src_towngen.py    License: MIT License 6 votes vote down vote up
def ccw(self,p0,p1,c):
        # Return 1 if p1 is counterclockwise from p0 with c as center; otherwise, return 0
        cx = c[0]
        cy = c[1]
        v0 = (p0.x-cx,p0.y-cy)
        v1 = (p1.x-cx,p1.y-cy)
        d0 = enorm(v0[0],v0[1])
        d1 = enorm(v1[0],v1[1])
        dp = (v0[0]*v1[0]) + (v0[1]*v1[1])
        if d0*d1 == 0:
            return 0
        q = clamp(dp/exclus(d0*d1),-1,1)
        ang = math.acos(q)
        if ang >= 0:
            return 1
        else:
            return 0 
Example 11
Project: pynomo   Author: lefakkomies   File: math_utilities.py    License: GNU General Public License v3.0 6 votes vote down vote up
def check_order(self, x1, y1, x2, y2, x3, y3, x4, y4):
        """
        makes sure that quadrilateral has order 1-2-4-3
        calculates angles around
        """

        def angle(v1, v2):
            v1_l = np.sqrt(v1[0] ** 2 + v1[1] ** 2)
            v2_l = np.sqrt(v2[0] ** 2 + v2[1] ** 2)
            return math.acos(np.dot(v1, v2) / (v1_l * v2_l))

        v21 = np.array([x2 - x1, y2 - y1])
        v42 = np.array([x4 - x2, y4 - y2])
        v34 = np.array([x3 - x4, y3 - y4])
        v13 = np.array([x1 - x3, y1 - y3])
        angle_1 = angle(v21, -v42)
        angle_2 = angle(v42, -v34)
        angle_3 = angle(v34, -v13)
        angle_4 = angle(v13, -v21)
        #print (angle_1 + angle_2 + angle_3 + angle_4)
        if abs((angle_1 + angle_2 + angle_3 + angle_4) - 2 * math.pi) < 1e-9:
            return x1, y1, x2, y2, x3, y3, x4, y4
        else:
            return x1, y1, x2, y2, x4, y4, x3, y3 
Example 12
Project: Finance-Python   Author: alpha-miner   File: testAccumulatorsArithmetic.py    License: MIT License 6 votes vote down vote up
def testAcosFunction(self):
        ma5 = MovingAverage(5, 'close')
        holder = Acos(ma5)

        sampleClose = np.cos(self.sampleClose)

        for i, close in enumerate(sampleClose):
            data = {'close': close}
            ma5.push(data)
            holder.push(data)

            expected = math.acos(ma5.result())
            calculated = holder.result()
            self.assertAlmostEqual(calculated, expected, 12, "at index {0:d}\n"
                                                             "expected:   {1:f}\n"
                                                             "calculated: {2:f}".format(i, expected, calculated)) 
Example 13
Project: PyEngine3D   Author: ubuntunux   File: Transform.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def slerp(quaternion1, quaternion2, amount):
    num = amount
    num2 = 0.0
    num3 = 0.0
    num4 = np.dot(quaternion1, quaternion2)
    flag = False
    if num4 < 0.0:
        flag = True
        num4 = -num4
    if num4 > 0.999999:
        num3 = 1.0 - num
        num2 = -num if flag else num
    else:
        num5 = math.acos(num4)
        num6 = 1.0 / math.sin(num5)
        num3 = math.sin((1.0 - num) * num5) * num6
        num2 = (-math.sin(num * num5) * num6) if flag else (math.sin(num * num5) * num6)
    return (num3 * quaternion1) + (num2 * quaternion2) 
Example 14
Project: robosuite   Author: StanfordVL   File: transform_utils.py    License: MIT License 5 votes vote down vote up
def quat_slerp(quat0, quat1, fraction, spin=0, shortestpath=True):
    """Return spherical linear interpolation between two quaternions.
    >>> q0 = random_quat()
    >>> q1 = random_quat()
    >>> q = quat_slerp(q0, q1, 0.0)
    >>> np.allclose(q, q0)
    True
    >>> q = quat_slerp(q0, q1, 1.0, 1)
    >>> np.allclose(q, q1)
    True
    >>> q = quat_slerp(q0, q1, 0.5)
    >>> angle = math.acos(np.dot(q0, q))
    >>> np.allclose(2.0, math.acos(np.dot(q0, q1)) / angle) or \
        np.allclose(2.0, math.acos(-np.dot(q0, q1)) / angle)
    True
    """
    q0 = unit_vector(quat0[:4])
    q1 = unit_vector(quat1[:4])
    if fraction == 0.0:
        return q0
    elif fraction == 1.0:
        return q1
    d = np.dot(q0, q1)
    if abs(abs(d) - 1.0) < _EPS:
        return q0
    if shortestpath and d < 0.0:
        # invert rotation
        d = -d
        q1 *= -1.0
    angle = math.acos(d) + spin * math.pi
    if abs(angle) < _EPS:
        return q0
    isin = 1.0 / math.sin(angle)
    q0 *= math.sin((1.0 - fraction) * angle) * isin
    q1 *= math.sin(fraction * angle) * isin
    q0 += q1
    return q0 
Example 15
Project: dogTorch   Author: ehsanik   File: metrics.py    License: MIT License 5 votes vote down vote up
def get_angle_diff(self, q1, q2):
        q1 = Quaternion(q1)
        q2 = Quaternion(q2)
        return math.acos(2 * (np.dot(q1.normalised.q, q2.normalised.q)**2) - 1) 
Example 16
Project: transferlearning   Author: jindongwang   File: intra_alignment.py    License: MIT License 5 votes vote down vote up
def getAngle(Ps, Pt, DD):
    
    Q = np.hstack((Ps, scipy.linalg.null_space(Ps.T)))
    dim = Pt.shape[1]
    QPt = Q.T @ Pt
    A, B = QPt[:dim, :], QPt[dim:, :]
    U,V,X,C,S = gsvd(A, B)
    alpha = np.zeros([1, DD])
    for i in range(DD):
        alpha[0][i] = math.sin(np.real(math.acos(C[i][i]*math.pi/180)))
    
    return alpha 
Example 17
Project: dump1090-tools   Author: mutability   File: fetch-dump1090-max-range.py    License: ISC License 5 votes vote down vote up
def greatcircle(lat0, lon0, lat1, lon1):
    lat0 = lat0 * math.pi / 180.0;
    lon0 = lon0 * math.pi / 180.0;
    lat1 = lat1 * math.pi / 180.0;
    lon1 = lon1 * math.pi / 180.0;
    return 6371e3 * math.acos(math.sin(lat0) * math.sin(lat1) + math.cos(lat0) * math.cos(lat1) * math.cos(abs(lon0 - lon1))) 
Example 18
Project: dump1090-tools   Author: mutability   File: dump1090.py    License: ISC License 5 votes vote down vote up
def greatcircle(lat0, lon0, lat1, lon1):
    lat0 = lat0 * math.pi / 180.0;
    lon0 = lon0 * math.pi / 180.0;
    lat1 = lat1 * math.pi / 180.0;
    lon1 = lon1 * math.pi / 180.0;
    return 6371e3 * math.acos(math.sin(lat0) * math.sin(lat1) + math.cos(lat0) * math.cos(lat1) * math.cos(abs(lon0 - lon1))) 
Example 19
Project: suncalcPy   Author: Broham   File: suncalc.py    License: MIT License 5 votes vote down vote up
def hourAngle(h, phi, d):
	try:
		ret = acos((sin(h) - sin(phi) * sin(d)) / (cos(phi) * cos(d)))
		return ret
	except ValueError as e:
		print(h, phi, d)
		print e 
Example 20
Project: suncalcPy   Author: Broham   File: suncalc.py    License: MIT License 5 votes vote down vote up
def getMoonIllumination(date):
    d = toDays(date)
    s = sunCoords(d)
    m = moonCoords(d)

	# distance from Earth to Sun in km
    sdist = 149598000
    phi = acos(sin(s["dec"]) * sin(m["dec"]) + cos(s["dec"]) * cos(m["dec"]) * cos(s["ra"] - m["ra"]))
    inc = atan(sdist * sin(phi), m["dist"] - sdist * cos(phi))
    angle = atan(cos(s["dec"]) * sin(s["ra"] - m["ra"]), sin(s["dec"]) * cos(m["dec"]) - cos(s["dec"]) * sin(m["dec"]) * cos(s["ra"] - m["ra"]));

    return dict(fraction=(1 + cos(inc)) / 2, phase= 0.5 + 0.5 * inc * (-1 if angle < 0 else 1) / PI, angle= angle) 
Example 21
Project: Localization   Author: kamalshadi   File: geometry.py    License: MIT License 5 votes vote down vote up
def angle(self, *args):
        x = self.dx
        y = self.dy
        z = self.dz

        if len(args) == 0:
            if self.mag() < res:
                return 0.0
            if x >= 0 and y >= 0:
                try:
                    return math.atan(y / x)
                except ZeroDivisionError:
                    return math.pi / 2
            elif x < 0 and y >= 0:
                return math.pi - math.atan(y / abs(x))
            elif x >= 0 and y < 0:
                try:
                    return -math.atan(abs(y) / x)
                except ZeroDivisionError:
                    return -math.pi / 2
            else:
                return math.atan(abs(y) / abs(x)) - math.pi
        elif len(args) == 1:
            b = args[0]
            try:
                rv = math.acos(self.dot(b) / (self.mag() * b.mag()))
                return rv
            except ZeroDivisionError:
                return 0.0 
Example 22
Project: hadrian   Author: modelop   File: pfamath.py    License: Apache License 2.0 5 votes vote down vote up
def __call__(self, state, scope, pos, paramTypes, x):
        try:
            return math.acos(x)
        except ValueError:
            return float("nan") 
Example 23
Project: rai-python   Author: MarcToussaint   File: transformations.py    License: MIT License 5 votes vote down vote up
def quaternion_slerp(quat0, quat1, fraction, spin=0, shortestpath=True):
    """Return spherical linear interpolation between two quaternions.
    >>> q0 = random_quaternion()
    >>> q1 = random_quaternion()
    >>> q = quaternion_slerp(q0, q1, 0.0)
    >>> numpy.allclose(q, q0)
    True
    >>> q = quaternion_slerp(q0, q1, 1.0, 1)
    >>> numpy.allclose(q, q1)
    True
    >>> q = quaternion_slerp(q0, q1, 0.5)
    >>> angle = math.acos(numpy.dot(q0, q))
    >>> numpy.allclose(2.0, math.acos(numpy.dot(q0, q1)) / angle) or \
        numpy.allclose(2.0, math.acos(-numpy.dot(q0, q1)) / angle)
    True
    """
    q0 = unit_vector(quat0[:4])
    q1 = unit_vector(quat1[:4])
    if fraction == 0.0:
        return q0
    elif fraction == 1.0:
        return q1
    d = numpy.dot(q0, q1)
    if abs(abs(d) - 1.0) < _EPS:
        return q0
    if shortestpath and d < 0.0:
        # invert rotation
        d = -d
        q1 *= -1.0
    angle = math.acos(d) + spin * math.pi
    if abs(angle) < _EPS:
        return q0
    isin = 1.0 / math.sin(angle)
    q0 *= math.sin((1.0 - fraction) * angle) * isin
    q1 *= math.sin(fraction * angle) * isin
    q0 += q1
    return q0 
Example 24
Project: honeybee   Author: ladybug-tools   File: euclid.py    License: GNU General Public License v3.0 5 votes vote down vote up
def angle(self, other):
        """Return the angle to the vector other"""
        return math.acos(self.dot(other) / (self.magnitude() * other.magnitude())) 
Example 25
Project: honeybee   Author: ladybug-tools   File: euclid.py    License: GNU General Public License v3.0 5 votes vote down vote up
def angle(self, other):
        """Return the angle to the vector other"""
        return math.acos(self.dot(other) / (self.magnitude() * other.magnitude())) 
Example 26
Project: honeybee   Author: ladybug-tools   File: euclid.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_angle_axis(self):
        if self.w > 1:
            self = self.normalized()
        angle = 2 * math.acos(self.w)
        s = math.sqrt(1 - self.w ** 2)
        if s < 0.001:
            return angle, Vector3(1, 0, 0)
        else:
            return angle, Vector3(self.x / s, self.y / s, self.z / s) 
Example 27
Project: honeybee   Author: ladybug-tools   File: euclid.py    License: GNU General Public License v3.0 5 votes vote down vote up
def new_interpolate(cls, q1, q2, t):
        assert isinstance(q1, Quaternion) and isinstance(q2, Quaternion)
        Q = cls()

        costheta = q1.w * q2.w + q1.x * q2.x + q1.y * q2.y + q1.z * q2.z
        if costheta < 0.:
            costheta = -costheta
            q1 = q1.conjugated()
        elif costheta > 1:
            costheta = 1

        theta = math.acos(costheta)
        if abs(theta) < 0.01:
            Q.w = q2.w
            Q.x = q2.x
            Q.y = q2.y
            Q.z = q2.z
            return Q

        sintheta = math.sqrt(1.0 - costheta * costheta)
        if abs(sintheta) < 0.01:
            Q.w = (q1.w + q2.w) * 0.5
            Q.x = (q1.x + q2.x) * 0.5
            Q.y = (q1.y + q2.y) * 0.5
            Q.z = (q1.z + q2.z) * 0.5
            return Q

        ratio1 = math.sin((1 - t) * theta) / sintheta
        ratio2 = math.sin(t * theta) / sintheta

        Q.w = q1.w * ratio1 + q2.w * ratio2
        Q.x = q1.x * ratio1 + q2.x * ratio2
        Q.y = q1.y * ratio1 + q2.y * ratio2
        Q.z = q1.z * ratio1 + q2.z * ratio2
        return Q 
Example 28
Project: rpg-text   Author: Dogeek   File: utils.py    License: MIT License 5 votes vote down vote up
def angle_to(self, other):
        other = Vector2(other)
        return math.acos(self.dot(other)/(self.magnitude*other.magnitude)) 
Example 29
Project: tributary   Author: timkpaine   File: ops.py    License: Apache License 2.0 5 votes vote down vote up
def Arccos(self):
    return unary(self, 'arccos(' + self._name_no_id() + ')', (lambda x: math.acos(self.value()))) 
Example 30
Project: tributary   Author: timkpaine   File: ops.py    License: 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].__truediv__(inputs[1])
        else:
            return inputs[1].__truediv__(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].asin()
    elif ufunc == np.arccos:
        return inputs[0].acos()
    elif ufunc == np.arctan:
        return inputs[0].atan()
    elif ufunc == np.exp:
        return inputs[0].exp()
    elif ufunc == sp.special.erf:
        return inputs[0].erf()
    raise NotImplementedError('Not Implemented!')