import math


def euler_angles_from_rotation_matrix(R):
    """From the paper by Gregory G. Slabaugh,
        Computing Euler angles from a rotation matrix
        psi, theta, phi = roll pitch yaw (x, y, z)

    Args:
      R: rotation matrix, a 3x3 numpy array

    Returns:
      a tuple with the 3 values psi, theta, phi in radians
    """

    def isclose(x, y, rtol=1.0e-5, atol=1.0e-8):
        return abs(x - y) <= atol + rtol * abs(y)

    phi = 0.0
    if isclose(R[2, 0], -1.0):
        theta = math.pi / 2.0
        psi = math.atan2(R[0, 1], R[0, 2])
    elif isclose(R[2, 0], 1.0):
        theta = -math.pi / 2.0
        psi = math.atan2(-R[0, 1], -R[0, 2])
    else:
        theta = -math.asin(R[2, 0])
        cos_theta = math.cos(theta)
        psi = math.atan2(R[2, 1] / cos_theta, R[2, 2] / cos_theta)
        phi = math.atan2(R[1, 0] / cos_theta, R[0, 0] / cos_theta)
    return psi, theta, phi