Python math.acos() Examples

The following are 30 code examples of math.acos(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module math , or try the search function .
Example #1
Source File: src_towngen.py    From Python-world-gen with 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 #2
Source File: metrics.py    From dogTorch with 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 #3
Source File: Transform.py    From PyEngine3D with 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 #4
Source File: gendaylit.py    From honeybee with 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
Source File: testAccumulatorsArithmetic.py    From Finance-Python with 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 #6
Source File: pose_error.py    From bop_toolkit with 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 #7
Source File: math_utilities.py    From pynomo with 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 #8
Source File: vector.py    From miRge with 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 #9
Source File: geometry.py    From Localization with 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 #10
Source File: geometry.py    From Localization with 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 #11
Source File: macros.py    From pyth with 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 #12
Source File: fao.py    From PyETo with 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 #13
Source File: linalg.py    From NURBS-Python with 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 #14
Source File: pose_error.py    From patch_linemod with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def re(R_est, R_gt):
    """
    Rotational Error.

    :param R_est: Rotational element of the estimated pose (3x1 vector).
    :param R_gt: Rotational element of the ground truth pose (3x1 vector).
    :return: Error of t_est w.r.t. t_gt.
    """
    assert(R_est.shape == R_gt.shape == (3, 3))
    error_cos = 0.5 * (np.trace(R_est.dot(np.linalg.inv(R_gt))) - 1.0)
    error_cos = min(1.0, max(-1.0, error_cos)) # Avoid invalid values due to numerical errors
    error = math.acos(error_cos)
    error = 180.0 * error / np.pi # [rad] -> [deg]
    return error 
Example #15
Source File: base.py    From orbit-predictor with MIT License 5 votes vote down vote up
def off_nadir_deg(self):
        """Computes off-nadir angle calculation

        Given satellite position ``sate_pos``, velocity ``sate_vel``, and
        location ``target`` in a common frame, off-nadir angle ``off_nadir_angle``
        is given by:
            t2b = sate_pos - target
            cos(off_nadir_angle) =     (sate_pos  · t2b)     # Vectorial dot product
                                    _______________________
                                    || sate_pos || || t2b||

        Sign for the rotation is calculated this way

        cross = target ⨯ sate_pos
        sign =   cross · sate_vel
               ____________________
               | cross · sate_vel |
        """
        sate_pos = self.max_elevation_position.position_ecef
        sate_vel = self.max_elevation_position.velocity_ecef
        target = self.location.position_ecef
        t2b = vector_diff(sate_pos, target)
        angle = acos(
            dot_product(sate_pos, t2b) / (vector_norm(sate_pos) * vector_norm(t2b))
        )

        cross = cross_product(target, sate_pos)
        dot = dot_product(cross, sate_vel)
        try:
            sign = dot / abs(dot)
        except ZeroDivisionError:
            sign = 1

        return degrees(angle) * sign 
Example #16
Source File: transform.py    From patch_linemod with BSD 2-Clause "Simplified" 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)
    >>> numpy.allclose(q, q0)
    True
    >>> q = quaternion_slerp(q0, q1, 1, 1)
    >>> numpy.allclose(q, q1)
    True
    >>> q = quaternion_slerp(q0, q1, 0.5)
    >>> angle = math.acos(numpy.dot(q0, q))
    >>> numpy.allclose(2, math.acos(numpy.dot(q0, q1)) / angle) or \
        numpy.allclose(2, 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
        numpy.negative(q1, q1)
    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 #17
Source File: utils.py    From gaige with MIT License 5 votes vote down vote up
def angle(pt1, pt2):
	x1, y1 = pt1
	x2, y2 = pt2
	inner_product = x1*x2 + y1*y2
	len1 = math.hypot(x1, y1)
	len2 = math.hypot(x2, y2)
	return math.acos(inner_product/(len1*len2)) 
Example #18
Source File: utils.py    From gaige with MIT License 5 votes vote down vote up
def angle(pt1, pt2):
	x1, y1 = pt1
	x2, y2 = pt2
	inner_product = x1*x2 + y1*y2
	len1 = math.hypot(x1, y1)
	len2 = math.hypot(x2, y2)
	return math.acos(inner_product/(len1*len2)) 
Example #19
Source File: utils.py    From gaige with MIT License 5 votes vote down vote up
def angle(pt1, pt2):
	x1, y1 = pt1
	x2, y2 = pt2
	inner_product = x1*x2 + y1*y2
	len1 = math.hypot(x1, y1)
	len2 = math.hypot(x2, y2)
	return math.acos(inner_product/(len1*len2)) 
Example #20
Source File: pose_error.py    From sixd_toolkit with MIT License 5 votes vote down vote up
def re(R_est, R_gt):
    """
    Rotational Error.

    :param R_est: Rotational element of the estimated pose (3x1 vector).
    :param R_gt: Rotational element of the ground truth pose (3x1 vector).
    :return: Error of t_est w.r.t. t_gt.
    """
    assert(R_est.shape == R_gt.shape == (3, 3))
    error_cos = 0.5 * (np.trace(R_est.dot(np.linalg.inv(R_gt))) - 1.0)
    error_cos = min(1.0, max(-1.0, error_cos)) # Avoid invalid values due to numerical errors
    error = math.acos(error_cos)
    error = 180.0 * error / np.pi # [rad] -> [deg]
    return error 
Example #21
Source File: geo.py    From kotori with GNU Affero General Public License v3.0 5 votes vote down vote up
def calculate_distance_and_bearing(from_lat_dec,from_long_dec,to_lat_dec,to_long_dec):
	"""Uses the spherical law of cosines to calculate the distance and bearing between two positions"""

	# Turn them all into radians
	from_theta = float(from_lat_dec)  / 360.0 * 2.0 * math.pi
	from_landa = float(from_long_dec) / 360.0 * 2.0 * math.pi
	to_theta = float(to_lat_dec)  / 360.0 * 2.0 * math.pi
	to_landa = float(to_long_dec) / 360.0 * 2.0 * math.pi

	d = math.acos(
			math.sin(from_theta) * math.sin(to_theta) +
			math.cos(from_theta) * math.cos(to_theta) * math.cos(to_landa-from_landa)
		) * earths_radius

	bearing = math.atan2(
			math.sin(to_landa-from_landa) * math.cos(to_theta),
			math.cos(from_theta) * math.sin(to_theta) -
			math.sin(from_theta) * math.cos(to_theta) * math.cos(to_landa-from_landa)
		)
	bearing = bearing / 2.0 / math.pi * 360.0

	return [d,bearing]

##############################################################
#            Easting/Northing Transform Methods              #
############################################################## 
Example #22
Source File: math.py    From myo-python with MIT License 5 votes vote down vote up
def angle_to(self, rhs):
    """
    Return the angle between this vector and *rhs* in radians.
    """

    return math.acos(self.dot(rhs) / (self.magnitude() * rhs.magnitude())) 
Example #23
Source File: transform.py    From pygcode with GNU General Public License v3.0 5 votes vote down vote up
def get_max_wedge_angle(self):
        """Calculate angular coverage of a single line reaching maximum allowable error"""
        d_radius = self.max_error / 2.
        return abs(2. * acos((self.arc_radius - d_radius) / (self.arc_radius + d_radius))) 
Example #24
Source File: transform.py    From pygcode with GNU General Public License v3.0 5 votes vote down vote up
def get_max_wedge_angle(self):
        """Calculate angular coverage of a single line reaching maximum allowable error"""
        return abs(2 * acos(self.arc_radius / (self.arc_radius + self.max_error))) 
Example #25
Source File: transform.py    From pygcode with GNU General Public License v3.0 5 votes vote down vote up
def get_max_wedge_angle(self):
        """Calculate angular coverage of a single line reaching maximum allowable error"""
        return abs(2 * acos((self.arc_radius - self.max_error) / self.arc_radius)) 
Example #26
Source File: scenario_helper.py    From scenario_runner with MIT License 5 votes vote down vote up
def generate_target_waypoint_list(waypoint, turn=0):
    """
    This method follow waypoints to a junction and choose path based on turn input.
    Turn input: LEFT -> -1, RIGHT -> 1, STRAIGHT -> 0
    @returns a waypoint list from the starting point to the end point according to turn input
    """
    reached_junction = False
    threshold = math.radians(0.1)
    plan = []
    while True:
        wp_choice = waypoint.next(2)
        if len(wp_choice) > 1:
            reached_junction = True
            waypoint = choose_at_junction(waypoint, wp_choice, turn)
        else:
            waypoint = wp_choice[0]
        plan.append((waypoint, RoadOption.LANEFOLLOW))
        #   End condition for the behavior
        if turn != 0 and reached_junction and len(plan) >= 3:
            v_1 = vector(
                plan[-2][0].transform.location,
                plan[-1][0].transform.location)
            v_2 = vector(
                plan[-3][0].transform.location,
                plan[-2][0].transform.location)
            angle_wp = math.acos(
                np.dot(v_1, v_2) / abs((np.linalg.norm(v_1) * np.linalg.norm(v_2))))
            if angle_wp < threshold:
                break
        elif reached_junction and not plan[-1][0].is_intersection:
            break

    return plan, plan[-1][0] 
Example #27
Source File: vec.py    From RLBotPythonExample with MIT License 5 votes vote down vote up
def ang_to(self, ideal: 'Vec3') -> float:
        """Returns the angle to the ideal vector. Angle will be between 0 and pi."""
        cos_ang = self.dot(ideal) / (self.length() * ideal.length())
        return math.acos(cos_ang) 
Example #28
Source File: test_math.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def testAcos(self):
        self.assertRaises(TypeError, math.acos)
        self.ftest('acos(-1)', math.acos(-1), math.pi)
        self.ftest('acos(0)', math.acos(0), math.pi/2)
        self.ftest('acos(1)', math.acos(1), 0)
        self.assertRaises(ValueError, math.acos, INF)
        self.assertRaises(ValueError, math.acos, NINF)
        self.assertTrue(math.isnan(math.acos(NAN))) 
Example #29
Source File: euclid.py    From renpy-shader with MIT License 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 #30
Source File: euclid.py    From renpy-shader with MIT License 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)