Python math.asin() Examples

The following are code examples for showing how to use math.asin(). 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: AboveTustin   Author: kevinabrandon   File: geomath.py    MIT License 6 votes vote down vote up
def distance(pointA, pointB):
	"""
	Calculate the great circle distance between two points 
	on the earth (specified in decimal degrees)

	http://stackoverflow.com/questions/15736995/how-can-i-quickly-estimate-the-distance-between-two-latitude-longitude-points
	"""
	# convert decimal degrees to radians 
	lon1, lat1, lon2, lat2 = map(math.radians, [pointA[1], pointA[0], pointB[1], pointB[0]])

	# haversine formula 
	dlon = lon2 - lon1 
	dlat = lat2 - lat1 
	a = math.sin(dlat/2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon/2)**2
	c = 2 * math.asin(math.sqrt(a)) 
	r = 3956  # Radius of earth in miles. Use 6371 for kilometers
	return c * r 
Example 2
Project: UR5_Controller   Author: tsinghua-rll   File: quaternion.py    MIT License 6 votes vote down vote up
def to_euler(q):
    # rpy
    sinr = 2.0 * (q[0] * q[1] + q[2] * q[3])
    cosr = 1.0 - 2.0 * (q[1] * q[1] + q[2] * q[2])
    roll = math.atan2(sinr, cosr)

    sinp = 2.0 * (q[0] * q[2] - q[3] * q[1])
    if math.fabs(sinp) >= 1.:
        pitch = math.copysign(np.pi / 2., sinp)
    else:
        pitch = math.asin(sinp)

    siny = 2.0 * (q[0] * q[3] + q[1] * q[2])
    cosy = 1.0 - 2.0 * (q[2] * q[2] + q[3] * q[3])
    yaw = math.atan2(siny, cosy)

    return np.asarray((roll, pitch, yaw), np.float32) 
Example 3
Project: streetview_objectmapping   Author: vlkryl   File: objectmapping.py    MIT License 6 votes vote down vote up
def haversine(lon1, lat1, lon2, lat2):
    """
    Calculate the great circle distance between two points 
    on the earth (specified in decimal degrees)
    """
    # convert decimal degrees to radians 
    lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
    # haversine formula 
    dlon = lon2 - lon1 
    dlat = lat2 - lat1 
    a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
    c = 2 * asin(sqrt(a)) 
    m = 6367000. * c
    return m

# calculating the intersection  point between two rays (specified each by camera position and depth-estimated object location) 
Example 4
Project: RLBotPack   Author: RLBot   File: sniper.py    MIT License 6 votes vote down vote up
def do_aiming_state(self):
        self.expected_hit_pos, travel_time = self.predict_hit_pos(self.info.my_car.aim_pos)
        self.expected_hit_time = self.info.time + travel_time
        self.direction = d = normalize(self.expected_hit_pos - self.info.my_car.aim_pos)

        rotation = Rotator(math.asin(d.z), math.atan2(d.y, d.x), 0)
        car_state = CarState(Physics(location=to_fb(self.info.my_car.aim_pos),
                                     velocity=Vector3(0, 0, 0),
                                     rotation=rotation,
                                     angular_velocity=Vector3(0, 0, 0)))
        game_state = GameState(cars={self.index: car_state})
        self.set_game_state(game_state)

        if self.next_flight_start_time < self.info.time:
            self.state = self.FLYING
            if self.next_is_super:
                self.doing_super = True
                self.next_is_super = False
            else:
                self.doing_super = False 
Example 5
Project: airqdata   Author: dr-1   File: utils.py    GNU General Public License v3.0 6 votes vote down vote up
def haversine(lat1, lon1, lat2, lon2):
    """Calculate the great circle distance between two points on earth.

    Args:
        lat1, lon1, lat2, lon2: coordinates of point 1 and point 2 in
            decimal degrees

    Returns:
        Distance in kilometers
    """

    # Convert decimal degrees to radians
    lat1, lon1, lat2, lon2 = (radians(val) for val in (lat1, lon1, lat2, lon2))

    # Haversine formula
    d_lat = lat2 - lat1
    d_lon = lon2 - lon1
    a = sin(d_lat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(d_lon / 2) ** 2
    c = 2 * asin(sqrt(a))
    radius = 6371  # Radius of earth in kilometers
    distance = c * radius

    return distance 
Example 6
Project: graph-keyword-search   Author: usc-isi-i2   File: util.py    Apache License 2.0 6 votes vote down vote up
def haversine(lon1, lat1, lon2, lat2, unit='mi'):
    """
    Calculate the great circle distance between two points 
    on the earth (specified in decimal degrees)
    """
    # convert decimal degrees to radians 
    lon1, lat1, lon2, lat2 = list(map(radians, [lon1, lat1, lon2, lat2]))
    # haversine formula 
    dlon = lon2 - lon1 
    dlat = lat2 - lat1 
    # print "dlat=%r,dlon=%r" % (dlat, dlon)
    a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
    c = 2 * asin(sqrt(a)) 
    
    distance = {'km': 6367,
                'mi': 3956,
                'ft': 20889110}[unit] * c
    return distance


# brought in from context.py r23462 
Example 7
Project: TripInference   Author: SUTDMEC   File: getActivities.py    MIT License 6 votes vote down vote up
def great_circle_dist(a, b, unit="kilometers"):
    """
    compute great circle distance between two latitude/longitude coordinate pairs.
    Returns great cirlce distance in kilometers (default) or meters.
    https://en.wikipedia.org/wiki/Great-circle_distance
    """
    lat1, lon1 = a
    lat2, lon2 = b
    if (lat1==92) or (lat2==92):
        return -1 # invalid location gives invalid distance
    dlat = math.radians(lat2 - lat1)
    dlon = math.radians(lon2 - lon1)
    a = (math.sin(dlat / 2.0) * math.sin(dlat / 2.0) +
            math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * 
            math.sin(dlon / 2.0) * math.sin(dlon / 2.0))
    c = 2.0 * math.asin(math.sqrt(a))
    dist_km = earth_radius * c
    if unit == "kilometers":
        return dist_km
    elif unit == "meters":
        return dist_km * 1000
    else:
        raise ValueError("Unknown unit: %s" % unit) 
Example 8
Project: honeybee   Author: ladybug-tools   File: euclid.py    GNU General Public License v3.0 6 votes vote down vote up
def get_euler(self):
        t = self.x * self.y + self.z * self.w
        if t > 0.4999:
            heading = 2 * math.atan2(self.x, self.w)
            attitude = math.pi / 2
            bank = 0
        elif t < -0.4999:
            heading = -2 * math.atan2(self.x, self.w)
            attitude = -math.pi / 2
            bank = 0
        else:
            sqx = self.x ** 2
            sqy = self.y ** 2
            sqz = self.z ** 2
            heading = math.atan2(2 * self.y * self.w - 2 * self.x * self.z,
                                 1 - 2 * sqy - 2 * sqz)
            attitude = math.asin(2 * t)
            bank = math.atan2(2 * self.x * self.w - 2 * self.y * self.z,
                              1 - 2 * sqx - 2 * sqz)
        return heading, attitude, bank 
Example 9
Project: vo_single_camera_sos   Author: ubuntuslave   File: euclid.py    GNU General Public License v3.0 6 votes vote down vote up
def get_euler(self):
        t = self.x * self.y + self.z * self.w
        if t > 0.4999:
            heading = 2 * math.atan2(self.x, self.w)
            attitude = math.pi / 2
            bank = 0
        elif t < -0.4999:
            heading = -2 * math.atan2(self.x, self.w)
            attitude = -math.pi / 2
            bank = 0
        else:
            sqx = self.x ** 2
            sqy = self.y ** 2
            sqz = self.z ** 2
            heading = math.atan2(2 * self.y * self.w - 2 * self.x * self.z,
                                 1 - 2 * sqy - 2 * sqz)
            attitude = math.asin(2 * t)
            bank = math.atan2(2 * self.x * self.w - 2 * self.y * self.z,
                              1 - 2 * sqx - 2 * sqz)
        return heading, attitude, bank 
Example 10
Project: 2018-1-OSS-E7   Author: 18-1-SKKU-OSS   File: bmath.py    MIT License 6 votes vote down vote up
def getEulerRotation(self):
		"""return the Euler rotation angles
		ROTX(x) * ROTY(y) * ROTZ(z)"""
		#  cos(z)*cos(y)
		#			sin(z)*cos(y)
		#						-sin(y)
		# -sin(z)*cos(x)+cos(z)*sin(y)*sin(x)
		#			cos(z)*cos(x)+sin(z)*sin(y)*sin(x)
		#						cos(y)*sin(x)
		#  sin(z)*sin(x)+cos(z)*sin(y)*cos(x)
		#			-cos(z)*sin(x)+sin(z)*sin(y)*cos(x)
		#						cos(y)*cos(x)
		rx =  atan2(self[1][2], self[2][2])
		ry = -asin( self[0][2])
		rz =  atan2(self[0][1], self[0][0])
		return rx,ry,rz

	# ---------------------------------------------------------------------- 
Example 11
Project: pykeeb   Author: r4dr3fr4d   File: keyboard_matrix.py    MIT License 6 votes vote down vote up
def arc_rows(self, R):
        """
        This function 2-dimensionally projects the keyboard rows onto a 
        circle with radius R on the x-z axes.
        """

        #TODO: Make the focus of the circle adjustable

        unit_width = (self.row_spacing + self.mount_width)
        unitangle = degrees(2 * asin(unit_width / (2 * R)))

        focus_x = self.origin[0] + ((self.rows / 2) * unit_width)
        focus_z = self.origin[2] + R

        for row in range(self.rows):
            x = row * unit_width

            theta = -(((self.rows - 1) / 2) - row) * unitangle

            zt = focus_z - ((cos(radians(theta)) * R))
            xt = (focus_x + (sin(radians(theta)) * (R + 7))) - x
            self.rm[row] = [0, xt, zt, theta, 0, 0] 
Example 12
Project: pykeeb   Author: r4dr3fr4d   File: keyboard_matrix.py    MIT License 6 votes vote down vote up
def arc_cols(self, R):
        """
        This function 2-dimensionally projects the keyboard columns onto a 
        circle with radius R on the y-z axes.
        """

        #TODO: Make the focus of the circle adjustable

        unit_width = (self.column_spacing + self.mount_width)
        unitangle = degrees(2 * asin(unit_width / (2 * R)))

        focus_y = self.origin[0] + ((self.columns / 2) * unit_width)
        focus_z = self.origin[2] + R

        for col in range(self.columns):
            y = col * unit_width

            theta = -(((self.columns - 1) / 2) - col) * unitangle

            zt = focus_z - ((cos(radians(theta)) * R))
            yt = (focus_y + (sin(radians(theta)) * (R + 7))) - y
            self.cm[col] = [yt, 0, zt, 0, -theta, 0] 
Example 13
Project: Ridesharing-App-For-HK-Back-End   Author: eric19960304   File: utils.py    MIT License 6 votes vote down vote up
def haversineDistance(location1, location2):
    """
    Calculate the great circle distance between two points in meters
    on the earth (specified in decimal degrees)
    """
    # convert decimal degrees to radians 
    lat1 = location1['latitude']
    lon1 = location1['longitude']
    lat2 = location2['latitude']
    lon2 = location2['longitude']
    lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])

    # haversine formula 
    dlon = lon2 - lon1 
    dlat = lat2 - lat1 
    a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
    c = 2 * asin(sqrt(a)) 
    r = 6371 # Radius of earth in kilometers. Use 3956 for miles
    return c * r * 1000 
Example 14
Project: SherpaHighLevel   Author: Shedino   File: mavextra.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def roll_estimate(RAW_IMU,GPS_RAW_INT=None,ATTITUDE=None,SENSOR_OFFSETS=None, ofs=None, mul=None,smooth=0.7):
    '''estimate roll from accelerometer'''
    rx = RAW_IMU.xacc * 9.81 / 1000.0
    ry = RAW_IMU.yacc * 9.81 / 1000.0
    rz = RAW_IMU.zacc * 9.81 / 1000.0
    if ATTITUDE is not None and GPS_RAW_INT is not None:
        ry -= ATTITUDE.yawspeed * GPS_RAW_INT.vel*0.01
        rz += ATTITUDE.pitchspeed * GPS_RAW_INT.vel*0.01
    if SENSOR_OFFSETS is not None and ofs is not None:
        rx += SENSOR_OFFSETS.accel_cal_x
        ry += SENSOR_OFFSETS.accel_cal_y
        rz += SENSOR_OFFSETS.accel_cal_z
        rx -= ofs[0]
        ry -= ofs[1]
        rz -= ofs[2]
        if mul is not None:
            rx *= mul[0]
            ry *= mul[1]
            rz *= mul[2]
    return lowpass(degrees(-asin(ry/sqrt(rx**2+ry**2+rz**2))),'_roll',smooth) 
Example 15
Project: SherpaHighLevel   Author: Shedino   File: mavextra.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def pitch_estimate(RAW_IMU, GPS_RAW_INT=None,ATTITUDE=None, SENSOR_OFFSETS=None, ofs=None, mul=None, smooth=0.7):
    '''estimate pitch from accelerometer'''
    rx = RAW_IMU.xacc * 9.81 / 1000.0
    ry = RAW_IMU.yacc * 9.81 / 1000.0
    rz = RAW_IMU.zacc * 9.81 / 1000.0
    if ATTITUDE is not None and GPS_RAW_INT is not None:
        ry -= ATTITUDE.yawspeed * GPS_RAW_INT.vel*0.01
        rz += ATTITUDE.pitchspeed * GPS_RAW_INT.vel*0.01
    if SENSOR_OFFSETS is not None and ofs is not None:
        rx += SENSOR_OFFSETS.accel_cal_x
        ry += SENSOR_OFFSETS.accel_cal_y
        rz += SENSOR_OFFSETS.accel_cal_z
        rx -= ofs[0]
        ry -= ofs[1]
        rz -= ofs[2]
        if mul is not None:
            rx *= mul[0]
            ry *= mul[1]
            rz *= mul[2]
    return lowpass(degrees(asin(rx/sqrt(rx**2+ry**2+rz**2))),'_pitch',smooth) 
Example 16
Project: SherpaHighLevel   Author: Shedino   File: mavextra.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def roll_estimate(RAW_IMU,GPS_RAW_INT=None,ATTITUDE=None,SENSOR_OFFSETS=None, ofs=None, mul=None,smooth=0.7):
    '''estimate roll from accelerometer'''
    rx = RAW_IMU.xacc * 9.81 / 1000.0
    ry = RAW_IMU.yacc * 9.81 / 1000.0
    rz = RAW_IMU.zacc * 9.81 / 1000.0
    if ATTITUDE is not None and GPS_RAW_INT is not None:
        ry -= ATTITUDE.yawspeed * GPS_RAW_INT.vel*0.01
        rz += ATTITUDE.pitchspeed * GPS_RAW_INT.vel*0.01
    if SENSOR_OFFSETS is not None and ofs is not None:
        rx += SENSOR_OFFSETS.accel_cal_x
        ry += SENSOR_OFFSETS.accel_cal_y
        rz += SENSOR_OFFSETS.accel_cal_z
        rx -= ofs[0]
        ry -= ofs[1]
        rz -= ofs[2]
        if mul is not None:
            rx *= mul[0]
            ry *= mul[1]
            rz *= mul[2]
    return lowpass(degrees(-asin(ry/sqrt(rx**2+ry**2+rz**2))),'_roll',smooth) 
Example 17
Project: SherpaHighLevel   Author: Shedino   File: mavextra.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def pitch_estimate(RAW_IMU, GPS_RAW_INT=None,ATTITUDE=None, SENSOR_OFFSETS=None, ofs=None, mul=None, smooth=0.7):
    '''estimate pitch from accelerometer'''
    rx = RAW_IMU.xacc * 9.81 / 1000.0
    ry = RAW_IMU.yacc * 9.81 / 1000.0
    rz = RAW_IMU.zacc * 9.81 / 1000.0
    if ATTITUDE is not None and GPS_RAW_INT is not None:
        ry -= ATTITUDE.yawspeed * GPS_RAW_INT.vel*0.01
        rz += ATTITUDE.pitchspeed * GPS_RAW_INT.vel*0.01
    if SENSOR_OFFSETS is not None and ofs is not None:
        rx += SENSOR_OFFSETS.accel_cal_x
        ry += SENSOR_OFFSETS.accel_cal_y
        rz += SENSOR_OFFSETS.accel_cal_z
        rx -= ofs[0]
        ry -= ofs[1]
        rz -= ofs[2]
        if mul is not None:
            rx *= mul[0]
            ry *= mul[1]
            rz *= mul[2]
    return lowpass(degrees(asin(rx/sqrt(rx**2+ry**2+rz**2))),'_pitch',smooth) 
Example 18
Project: 3DCT   Author: coraxx   File: QtCustom.py    GNU General Public License v3.0 6 votes vote down vote up
def addArrow(self,start,end,arrowangle=45,color=QtCore.Qt.red):
		dx, dy = map(lambda a,b: a - b, end, start)
		length = math.hypot(dx,dy)
		angle = -(math.asin(dy / length))
		if dx < 0:
			angle = math.radians(180) - angle
		if debug is True: print clrmsg.DEBUG + 'Radians:', angle, 'Degree', math.degrees(angle)
		path = QtGui.QPainterPath()
		path.moveTo(*start)
		path.lineTo(*end)
		path.arcMoveTo(
			end[0] - 0.25 * length, end[1] - 0.25 * length,
			0.5 * length, 0.5 * length,
			180 - arrowangle + math.degrees(angle))
		path.lineTo(*end)
		path.arcMoveTo(
			end[0] - 0.25 * length, end[1] - 0.25 * length,
			0.5 * length, 0.5 * length,
			180 + arrowangle + math.degrees(angle))
		path.lineTo(*end)
		self.addPath(path,QtGui.QPen(color)) 
Example 19
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 6 votes vote down vote up
def haversine_distance(point1, point2):
    '''
        Calculating haversine distance between two points
        (see https://en.wikipedia.org/wiki/Haversine_formula,
            https://www.math.ksu.edu/~dbski/writings/haversine.pdf)

        Is numerically better-conditioned for small distances
    '''
    lon1, lat1 = (radians(coord) for coord in point1[:2])
    lon2, lat2 = (radians(coord) for coord in point2[:2])
    dlat = (lat2 - lat1)
    dlon = (lon2 - lon1)
    a = (
        sin(dlat * 0.5)**2 +
        cos(lat1) * cos(lat2) * sin(dlon * 0.5)**2
    )

    return EARTH_MEAN_DIAMETER * asin(sqrt(a)) 
Example 20
Project: VCIVING-SpeechRecognition   Author: GENIVI   File: analyzers.py    Mozilla Public License 2.0 6 votes vote down vote up
def get_location_clusters(self):
        latitudes, longitudes = [], []
        for location in self._location_data:
            latitudes.append(location[consts_location_log.COLUMN_LATITUDE])
            longitudes.append(location[consts_location_log.COLUMN_LONGITUDE])

        np_locations = np.array([latitudes, longitudes]).T
        segment_cutoff_threshold_in_degrees = degrees(asin(sqrt(2) * sin((config_analyzers.SEGMENT_CUTOFF_THRESHOLD * consts_analyzers.KMS_IN_METER) / (2 * consts_analyzers.AVERAGE_EARTH_RADIUS))))
        np_locations_clusters = hcluster.fclusterdata(np_locations, segment_cutoff_threshold_in_degrees, criterion="distance")

        location_data_with_clusters = []
        for location_index, cluster in np.ndenumerate(np_locations_clusters):
            location_data = self._location_data[location_index[0]]
            location_data[consts_location_log.COLUMN_CLUSTER] = cluster
            location_data_with_clusters.append(location_data)

        return location_data_with_clusters 
Example 21
Project: snowballing   Author: JoaoFelipe   File: utils.py    MIT License 6 votes vote down vote up
def lines_len_in_circle(r, font_size=12, letter_width=7.2):
    """Return the amount of chars that fits each line in a circle according to
    its radius *r*

    Doctest:

    .. doctest::

        >>> lines_len_in_circle(20)
        [2, 5, 2]
    """
    lines = 2 * r // font_size
    positions = [
        x + (font_size // 2) * (-1 if x <= 0 else 1)
        for x in text_y(lines)
    ]
    return [
        int(2 * r * cos(asin(y / r)) / letter_width)
        for y in positions
    ] 
Example 22
Project: renpy-shader   Author: bitsawer   File: euclid.py    MIT License 6 votes vote down vote up
def get_euler(self):
        t = self.x * self.y + self.z * self.w
        if t > 0.4999:
            heading = 2 * math.atan2(self.x, self.w)
            attitude = math.pi / 2
            bank = 0
        elif t < -0.4999:
            heading = -2 * math.atan2(self.x, self.w)
            attitude = -math.pi / 2
            bank = 0
        else:
            sqx = self.x ** 2
            sqy = self.y ** 2
            sqz = self.z ** 2
            heading = math.atan2(2 * self.y * self.w - 2 * self.x * self.z,
                                 1 - 2 * sqy - 2 * sqz)
            attitude = math.asin(2 * t)
            bank = math.atan2(2 * self.x * self.w - 2 * self.y * self.z,
                              1 - 2 * sqx - 2 * sqz)
        return heading, attitude, bank 
Example 23
Project: CatalogueTool-Lite   Author: GEMScienceTools   File: CatUtils.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def WgsDistance(Lat1, Lon1, Lat2, Lon2):
  """
  Author: Salvador Dali
  http://stackoverflow.com/users/1090562/salvador-dali
  """

  p = 0.017453292519943295

  c1 = ma.cos((Lat2 - Lat1) * p)
  c2 = ma.cos(Lat1 * p)
  c3 = ma.cos(Lat2 * p)
  c4 = ma.cos((Lon2 - Lon1) * p)

  a = 0.5 - c1/2 + c2 * c3 * (1 - c4) / 2

  return 12742 * ma.asin(ma.sqrt(a))

#----------------------------------------------------------------------------------------- 
Example 24
Project: pyblish-win   Author: pyblish   File: test_math.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testAsin(self):
        self.assertRaises(TypeError, math.asin)
        self.ftest('asin(-1)', math.asin(-1), -math.pi/2)
        self.ftest('asin(0)', math.asin(0), 0)
        self.ftest('asin(1)', math.asin(1), math.pi/2)
        self.assertRaises(ValueError, math.asin, INF)
        self.assertRaises(ValueError, math.asin, NINF)
        self.assertTrue(math.isnan(math.asin(NAN))) 
Example 25
Project: mtrl-auto-uav   Author: brunapearson   File: utils.py    MIT License 5 votes vote down vote up
def to_eularian_angles(q):
    z = q.z_val
    y = q.y_val
    x = q.x_val
    w = q.w_val
    ysqr = y * y

    # roll (x-axis rotation)
    t0 = +2.0 * (w*x + y*z)
    t1 = +1.0 - 2.0*(x*x + ysqr)
    roll = math.atan2(t0, t1)

    # pitch (y-axis rotation)
    t2 = +2.0 * (w*y - z*x)
    if (t2 > 1.0):
        t2 = 1
    if (t2 < -1.0):
        t2 = -1.0
    pitch = math.asin(t2)

    # yaw (z-axis rotation)
    t3 = +2.0 * (w*z + x*y)
    t4 = +1.0 - 2.0 * (ysqr + z*z)
    yaw = math.atan2(t3, t4)

    return (pitch, roll, yaw) 
Example 26
Project: look_around   Author: iqbalhusen   File: haversine.py    MIT License 5 votes vote down vote up
def distance(origin, destination):
    """
    Calculate the great circle distance between two points 
    on the earth (specified in decimal degrees)
    """
    # convert decimal degrees to radians 
    lon1, lat1, lon2, lat2 = map(radians, origin + destination)

    # Haversine formula
    dlon = lon2 - lon1 
    dlat = lat2 - lat1 
    a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
    c = 2 * asin(sqrt(a)) 
    r = 6371  # Radius of earth in kilometers. Use 3956 for miles
    return c * r 
Example 27
Project: o2g   Author: hiposfer   File: gtfs_dummy.py    MIT License 5 votes vote down vote up
def haversine(lon1, lat1, lon2, lat2):
    """
    Calculate the great circle distance between two
    points on the earth (specified in decimal degrees)
    """
    # convert decimal degrees to radians
    lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])

    # haversine formula
    dlon = lon2 - lon1
    dlat = lat2 - lat1
    a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2
    c = 2 * asin(sqrt(a))
    r = 6371  # Radius of earth in kilometers. Use 3956 for miles
    return c * r 
Example 28
Project: Parallel.GAMIT   Author: demiangomez   File: pyVoronoi.py    GNU General Public License v3.0 5 votes vote down vote up
def calculate_haversine_distance_between_spherical_points(cartesian_array_1,cartesian_array_2,sphere_radius):
    '''Calculate the haversine-based distance between two points on the surface of a sphere. Should be more accurate than the arc cosine strategy. See, for example: http://en.wikipedia.org/wiki/Haversine_formula'''
    spherical_array_1 = convert_cartesian_array_to_spherical_array(cartesian_array_1)
    spherical_array_2 = convert_cartesian_array_to_spherical_array(cartesian_array_2)
    lambda_1 = spherical_array_1[1]
    lambda_2 = spherical_array_2[1]
    phi_1 = spherical_array_1[2]
    phi_2 = spherical_array_2[2]
    #we rewrite the standard Haversine slightly as long/lat is not the same as spherical coordinates - phi differs by pi/4
    spherical_distance = 2.0 * sphere_radius * math.asin(math.sqrt( ((1 - math.cos(phi_2-phi_1))/2.) + math.sin(phi_1) * math.sin(phi_2) * ( (1 - math.cos(lambda_2-lambda_1))/2.)  ))
    return spherical_distance 
Example 29
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 30
Project: dump1090-tools   Author: mutability   File: adsb-polar.py    ISC License 5 votes vote down vote up
def latlngup_to_relxyz(c,l):
    # this converts WGS84 (lat,lng,alt) to a rotated ECEF frame
    # where the earth center is still at the origin
    # but (clat,clng,calt) has been rotated to lie on the positive X axis

    clat,clng,calt = c
    llat,llng,lalt = l

    # rotate by -clng around Z to put C on the X/Z plane
    # (this is easy to do while still in WGS84 coordinates)
    llng = llng - clng

    # find angle between XY plane and C
    cx,cy,cz = latlngup_to_ecef((clat,0,calt))
    a = math.atan2(cz,cx)
    
    # convert L to (rotated around Z) ECEF
    lx,ly,lz = latlngup_to_ecef((llat,llng,lalt))

    # rotate by -a around Y to put C on the X axis
    asin = math.sin(-a)
    acos = math.cos(-a)
    rx = lx * acos - lz * asin
    rz = lx * asin + lz * acos

    return (rx, ly, rz)

# calculate range, bearing, elevation from C to L 
Example 31
Project: dump1090-tools   Author: mutability   File: adsb-polar.py    ISC License 5 votes vote down vote up
def range_bearing_elevation(c,l):
    # rotate C onto X axis
    crx, cry, crz = latlngup_to_relxyz(c,c)
    # rotate L in the same way
    lrx, lry, lrz = latlngup_to_relxyz(c,l)

    # Now we have cartesian coordinates with C on
    # the X axis with ground plane YZ and north along +Z.

    dx, dy, dz = lrx-crx, lry-cry, lrz-crz
    rng = math.sqrt(dx*dx + dy*dy + dz*dz)
    bearing = (360 + 90 - rtod(math.atan2(dz,dy))) % 360
    elev = rtod(math.asin(dx / rng))

    return (rng, bearing, elev) 
Example 32
Project: dump1090-tools   Author: mutability   File: adsb-polar-2.py    ISC License 5 votes vote down vote up
def latlngup_to_relxyz(c,l):
    # this converts WGS84 (lat,lng,alt) to a rotated ECEF frame
    # where the earth center is still at the origin
    # but (clat,clng,calt) has been rotated to lie on the positive X axis

    clat,clng,calt = c
    llat,llng,lalt = l

    # rotate by -clng around Z to put C on the X/Z plane
    # (this is easy to do while still in WGS84 coordinates)
    llng = llng - clng

    # find angle between XY plane and C
    cx,cy,cz = latlngup_to_ecef((clat,0,calt))
    a = math.atan2(cz,cx)

    # convert L to (rotated around Z) ECEF
    lx,ly,lz = latlngup_to_ecef((llat,llng,lalt))

    # rotate by -a around Y to put C on the X axis
    asin = math.sin(-a)
    acos = math.cos(-a)
    rx = lx * acos - lz * asin
    rz = lx * asin + lz * acos

    return (rx, ly, rz)

# great circle distance from C to L, assuming spherical geometry (~0.3% error)
# from http://www.movable-type.co.uk/scripts/latlong.html ("haversine formula") 
Example 33
Project: dump1090-tools   Author: mutability   File: adsb-polar-2.py    ISC License 5 votes vote down vote up
def range_bearing_elevation_from(c):
    # build a function that calculates ranges, bearing, elevation from C
    clat,clng,calt = c

    # rotate by -clng to put C on the XZ plane
    # find angle between XY plane and C
    cx,cy,cz = latlngup_to_ecef((clat,0,calt))
    a = math.atan2(cz,cx)
    
    # rotate by -a around Y to put C on the X axis
    asin = math.sin(-a)
    acos = math.cos(-a)

    crx = cx * acos - cz * asin
    cry = cy                         # should be zero
    crz = cx * asin + cz * acos      # should be zero

    def rbe(l):
        # rotate L into our new reference frame
        llat,llng,lalt = l
        # rotate by -clng, convert to ECEF
        lx,ly,lz = latlngup_to_ecef((llat,llng - clng,lalt))

        # rotate by -a around Y
        lrx = lx * acos - lz * asin
        lry = ly
        lrz = lx * asin + lz * acos

        # Now we have cartesian coordinates with C on
        # the +X axis, ground plane YZ, north along +Z.

        dx, dy, dz = lrx-crx, lry-cry, lrz-crz
        slant = math.sqrt(dx*dx + dy*dy + dz*dz)             # true line-of-sight range
        bearing = (360 + 90 - rtod(math.atan2(dz,dy))) % 360 # bearing around X axis
        elev = rtod(math.asin(dx / slant))                   # elevation from horizon (YZ plane)
        horiz_range = math.sqrt(dy*dy + dz*dz)               # distance projected onto YZ (ground/horizon plane); something like ground distance if the Earth was flat
        return (slant, horiz_range, bearing, elev, (lrx,lry,lrz))

    return rbe

# calculate true range, bearing, elevation from C to L 
Example 34
Project: dump1090-tools   Author: mutability   File: adsb-polar-2.py    ISC License 5 votes vote down vote up
def range_bearing_elevation(c,l):
    # rotate C onto X axis
    crx, cry, crz = latlngup_to_relxyz(c,c)
    # rotate L in the same way
    lrx, lry, lrz = latlngup_to_relxyz(c,l)

    # Now we have cartesian coordinates with C on
    # the +X axis, ground plane YZ, north along +Z.

    dx, dy, dz = lrx-crx, lry-cry, lrz-crz
    slant = math.sqrt(dx*dx + dy*dy + dz*dz)             # true line-of-sight range
    bearing = (360 + 90 - rtod(math.atan2(dz,dy))) % 360 # bearing around X axis
    elev = rtod(math.asin(dx / slant))                   # elevation from horizon (YZ plane)
    horiz_range = math.sqrt(dy*dy + dz*dz)               # distance projected onto YZ (ground/horizon plane); something like ground distance if the Earth was flat
    return (slant, horiz_range, bearing, elev, (lrx,lry,lrz)) 
Example 35
Project: quadcopter-simulation   Author: hbd730   File: utils.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def RotToRPY(R):
    phi = asin(R[1,2])
    theta = atan2(-R[0,2]/cos(phi),R[2,2]/cos(phi))
    psi = atan2(-R[1,0]/cos(phi),R[1,1]/cos(phi))
    return phi, theta, psi 
Example 36
Project: suncalcPy   Author: Broham   File: suncalc.py    MIT License 5 votes vote down vote up
def declination(l, b):    
	return asin(sin(b) * cos(e) + cos(b) * sin(e) * sin(l)) 
Example 37
Project: suncalcPy   Author: Broham   File: suncalc.py    MIT License 5 votes vote down vote up
def altitude(H, phi, dec):
	return asin(sin(phi) * sin(dec) + cos(phi) * cos(dec) * cos(H)) 
Example 38
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 39
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 40
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 41
Project: me-ica   Author: ME-ICA   File: test_euler.py    GNU Lesser General Public License v2.1 5 votes vote down vote up
def crude_mat2euler(M):
    ''' The simplest possible - ignoring atan2 instability '''
    r11, r12, r13, r21, r22, r23, r31, r32, r33 = M.flat
    return math.atan2(-r12, r11), math.asin(r13), math.atan2(-r23, r33) 
Example 42
Project: gcogen   Author: gcogen   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def arc(self, radius, to_x, to_y, cw = True):
        # current position of the tool
        curr_x, curr_y = self.t.position()
        # linear distance between curr and to
        d = math.sqrt((curr_x - to_x)**2 + (curr_y - to_y)**2)
        # distance between curr and perpendicular bisector
        d = d/2
        # getting the angle
        tetha = math.asin(d/radius)*180/math.pi
        # two times the tetha will give total angle
        angle = 2*tetha
        # give the values to arc_angle
        self.arc_angle(radius, angle, cw) 
Example 43
Project: geophys_utils   Author: GeoscienceAustralia   File: _vincenty.py    Apache License 2.0 5 votes vote down vote up
def __init__(self,rmajor,rminor,lon1,lat1,lon2,lat2):
        """
        Define a great circle by specifying:
        rmajor - radius of major axis of ellipsoid
        rminor - radius of minor axis of ellipsoid.
        lon1 - starting longitude of great circle
        lat1 - starting latitude
        lon2 - ending longitude
        lat2 - ending latitude
        All must be given in degrees.

        Instance variables:
        distance - distance along great circle in radians.
        lon1,lat1,lon2,lat2 - start and end points (in radians).
        """
        # convert to radians from degrees.
        lat1 = math.radians(lat1)
        lon1 = math.radians(lon1)
        lat2 = math.radians(lat2)
        lon2 = math.radians(lon2)
        self.a = rmajor
        self.f = (rmajor-rminor)/rmajor
        self.lat1 = lat1
        self.lat2 = lat2
        self.lon1 = lon1
        self.lon2 = lon2
        # distance along geodesic in meters.
        d,a12,a21 = vinc_dist(self.f,  self.a,  lat1,  lon1,  lat2,  lon2 )
        self.distance = d
        self.azimuth12 = a12
        self.azimuth21 = a21
        # great circle arc-length distance (in radians).
        self.gcarclen = 2.*math.asin(math.sqrt((math.sin((lat1-lat2)/2))**2+\
        math.cos(lat1)*math.cos(lat2)*(math.sin((lon1-lon2)/2))**2))
        # check to see if points are antipodal (if so, route is undefined).
        if self.gcarclen == math.pi:
            self.antipodal = True
        else:
            self.antipodal = False 
Example 44
Project: RouteOptimization   Author: andre-le   File: distance.py    MIT License 5 votes vote down vote up
def destination(self, point, bearing, distance=None): # pylint: disable=W0621
        """
        TODO docs.
        """
        point = Point(point)
        lat1 = units.radians(degrees=point.latitude)
        lng1 = units.radians(degrees=point.longitude)
        bearing = units.radians(degrees=bearing)

        if distance is None:
            distance = self
        if isinstance(distance, Distance):
            distance = distance.kilometers

        d_div_r = float(distance) / self.RADIUS

        lat2 = asin(
            sin(lat1) * cos(d_div_r) +
            cos(lat1) * sin(d_div_r) * cos(bearing)
        )

        lng2 = lng1 + atan2(
            sin(bearing) * sin(d_div_r) * cos(lat1),
            cos(d_div_r) - sin(lat1) * sin(lat2)
        )

        return Point(units.degrees(radians=lat2), units.degrees(radians=lng2)) 
Example 45
Project: NiujiaoDebugger   Author: MrSrc   File: test_math.py    GNU General Public License v3.0 5 votes vote down vote up
def testAsin(self):
        self.assertRaises(TypeError, math.asin)
        self.ftest('asin(-1)', math.asin(-1), -math.pi/2)
        self.ftest('asin(0)', math.asin(0), 0)
        self.ftest('asin(1)', math.asin(1), math.pi/2)
        self.assertRaises(ValueError, math.asin, INF)
        self.assertRaises(ValueError, math.asin, NINF)
        self.assertRaises(ValueError, math.asin, 1 + eps)
        self.assertRaises(ValueError, math.asin, -1 - eps)
        self.assertTrue(math.isnan(math.asin(NAN))) 
Example 46
Project: RobotPath   Author: kavehkamali   File: math3D.py    GNU General Public License v3.0 5 votes vote down vote up
def angle_axis(R):
    u=np.zeros(3)
    u[0]=R[2,1]-R[1,2]
    u[1]=R[0,2]-R[2,0]
    u[2]=R[1,0]-R[0,1]
    mag=sqrt(u[0]**2+u[1]**2+u[2]**2)
    u=u/mag
    angle=asin(mag/2)

    return angle, u 
Example 47
Project: Bilibili-   Author: ytx1991   File: GetAssDanmaku.py    MIT License 5 votes vote down vote up
def ConvertFlashRotation(rotY, rotZ, X, Y, width, height):
    def WrapAngle(deg):
        return 180-((180-deg) % 360)
    rotY = WrapAngle(rotY)
    rotZ = WrapAngle(rotZ)
    if rotY in (90, -90):
        rotY -= 1
    if rotY == 0 or rotZ == 0:
        outX = 0
        outY = -rotY  # Positive value means clockwise in Flash
        outZ = -rotZ
        rotY *= math.pi/180.0
        rotZ *= math.pi/180.0
    else:
        rotY *= math.pi/180.0
        rotZ *= math.pi/180.0
        outY = math.atan2(-math.sin(rotY)*math.cos(rotZ), math.cos(rotY))*180/math.pi
        outZ = math.atan2(-math.cos(rotY)*math.sin(rotZ), math.cos(rotZ))*180/math.pi
        outX = math.asin(math.sin(rotY)*math.sin(rotZ))*180/math.pi
    trX = (X*math.cos(rotZ)+Y*math.sin(rotZ))/math.cos(rotY)+(1-math.cos(rotZ)/math.cos(rotY))*width/2-math.sin(rotZ)/math.cos(rotY)*height/2
    trY = Y*math.cos(rotZ)-X*math.sin(rotZ)+math.sin(rotZ)*width/2+(1-math.cos(rotZ))*height/2
    trZ = (trX-width/2)*math.sin(rotY)
    FOV = width*math.tan(2*math.pi/9.0)/2
    try:
        scaleXY = FOV/(FOV+trZ)
    except ZeroDivisionError:
        logging.error('Rotation makes object behind the camera: trZ == %.0f' % trZ)
        scaleXY = 1
    trX = (trX-width/2)*scaleXY+width/2
    trY = (trY-height/2)*scaleXY+height/2
    if scaleXY < 0:
        scaleXY = -scaleXY
        outX += 180
        outY += 180
        logging.error('Rotation makes object behind the camera: trZ == %.0f < %.0f' % (trZ, FOV))
    return (trX, trY, WrapAngle(outX), WrapAngle(outY), WrapAngle(outZ), scaleXY*100, scaleXY*100) 
Example 48
Project: auv-control-pi   Author: adrienemery   File: calibrate_ahrs.py    MIT License 5 votes vote down vote up
def pitch(self):
        return degrees(-asin(2.0 * (self.q[1] * self.q[3] - self.q[0] * self.q[2]))) 
Example 49
Project: auv-control-pi   Author: adrienemery   File: ahrs.py    MIT License 5 votes vote down vote up
def pitch(self):
        if SIMULATION:
            return 0
        return degrees(-asin(2.0 * (self.q[1] * self.q[3] - self.q[0] * self.q[2]))) 
Example 50
Project: cookie-factory   Author: njanakiev   File: geometry.py    GNU General Public License v3.0 5 votes vote down vote up
def uv_from_vector(vector):
    x, y, z = vector.normalized()
    phi, theta = atan2(y, x), asin(z)
    u, v = (phi + PI)/TAU, (theta + PI/2)/PI

    return u, v 
Example 51
Project: ems   Author: mtils   File: geocoordinate.py    MIT License 5 votes vote down vote up
def atDistanceAndAzimuthStatic(coord, distance, azimuth):
        '''
        
        @param coord: The GeoCordinate
        @type coord: GeoCoordinate
        @param distance: The distance
        @type distance: int
        @param azimuth: The azimuth
        @type azimuth: int
        @return: tuple
        '''
        
        latRad = GeoCoordinate.degToRad(coord.lat)
        lonRad = GeoCoordinate.degToRad(coord.lng)
        cosLatRad = math.cos(latRad)
        sinLatRad = math.sin(latRad)
        
        azimuthRad = GeoCoordinate.degToRad(azimuth)
        
        ratio = (distance / GeoCoordinate.EARTH_MEAN_RADIUS * 1000.0)
        
        cosRatio = math.cos(ratio)
        sinRatio = math.sin(ratio)
        
        resultLatRad = math.asin(sinLatRad * cosRatio
                                 + cosLatRad * sinRatio * math.cos(azimuthRad))
        resultLonRad = lonRad +\
                       math.atan2(math.sin(azimuthRad) * sinRatio + cosLatRad,
                                  cosRatio - sinLatRad + math.sin(resultLatRad))
        
        return (GeoCoordinate.radToDeg(resultLatRad), GeoCoordinate.radToDeg(resultLonRad)) 
Example 52
Project: PyMO   Author: omimo   File: rotation_tools.py    MIT License 5 votes vote down vote up
def to_euler(self, use_deg=False):
        eulers = np.zeros((2, 3))

        if np.absolute(np.absolute(self.rotmat[2, 0]) - 1) < 1e-12:
            #GIMBAL LOCK!
            print('Gimbal')
            if np.absolute(self.rotmat[2, 0]) - 1 < 1e-12:
                eulers[:,0] = math.atan2(-self.rotmat[0,1], -self.rotmat[0,2])
                eulers[:,1] = -math.pi/2
            else:
                eulers[:,0] = math.atan2(self.rotmat[0,1], -elf.rotmat[0,2])
                eulers[:,1] = math.pi/2
            
            return eulers

        theta = - math.asin(self.rotmat[2,0])
        theta2 = math.pi - theta

        # psi1, psi2
        eulers[0,0] = math.atan2(self.rotmat[2,1]/math.cos(theta), self.rotmat[2,2]/math.cos(theta))
        eulers[1,0] = math.atan2(self.rotmat[2,1]/math.cos(theta2), self.rotmat[2,2]/math.cos(theta2))

        # theta1, theta2
        eulers[0,1] = theta
        eulers[1,1] = theta2

        # phi1, phi2
        eulers[0,2] = math.atan2(self.rotmat[1,0]/math.cos(theta), self.rotmat[0,0]/math.cos(theta))
        eulers[1,2] = math.atan2(self.rotmat[1,0]/math.cos(theta2), self.rotmat[0,0]/math.cos(theta2))

        if use_deg:
            eulers = rad2deg(eulers)

        return eulers 
Example 53
Project: slack-traffic   Author: alxwrd   File: trafficfeed.py    MIT License 5 votes vote down vote up
def haversine(lon1, lat1, lon2, lat2):
        """Calculate the great circle distance between two points
        on the earth (specified in decimal degrees)
        """
        # convert decimal degrees to radians
        lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
        # haversine formula
        dlon = lon2 - lon1
        dlat = lat2 - lat1
        a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
        c = 2 * asin(sqrt(a))
        km = 6367 * c
        return km 
Example 54
Project: rainmachine-developer-resources   Author: sprinkler   File: rmTimeUtils.py    GNU General Public License v3.0 5 votes vote down vote up
def __asina(x):
    if abs(x) > 1:
        return  -90. if  x< 0 else 90.
    radian = asin(x)
    return radian/(3.14159265359)*180. 
Example 55
Project: rucio   Author: rucio   File: replica_sorter.py    Apache License 2.0 5 votes vote down vote up
def __get_distance(se1, se2, ignore_error):
    """
    Get the distance between 2 host using the GeoLite DB
    :param se1 : A first hostname or IP.
    :param se2 : A second hostname or IP.
    :ignore_error: Ignore exception when the GeoLite DB cannot be retrieved
    """
    directory = '/tmp'
    ipv6_filename = 'GeoLite2-City'
    try:
        __get_geoip_db(directory, ipv6_filename)

        gi = geoip2.database.Reader('%s/%s' % (directory, '%s.mmdb' % ipv6_filename))

        lat1, long1 = __get_lat_long(se1, gi)
        lat2, long2 = __get_lat_long(se2, gi)

        if lat1 and lat2:
            long1, lat1, long2, lat2 = map(radians, [long1, lat1, long2, lat2])
            dlon = long2 - long1
            dlat = lat2 - lat1
            return 6378 * 2 * asin(sqrt(sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2))
    except Exception as error:
        if not ignore_error:
            raise error
    # One host is on the Moon
    return 360000 
Example 56
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 57
Project: PokemonGo-Bot   Author: PokemonGoF   File: utils.py    MIT License 5 votes vote down vote up
def distance(lat1, lon1, lat2, lon2):
    p = 0.017453292519943295
    a = 0.5 - cos((lat2 - lat1) * p) / 2 + cos(lat1 * p) * \
        cos(lat2 * p) * (1 - cos((lon2 - lon1) * p)) / 2
    return 12742 * asin(sqrt(a)) * 1000 
Example 58
Project: Geognomo   Author: ZYenGroupLimited   File: triangle.py    MIT License 5 votes vote down vote up
def getDistance(latitude1, longitude1, latitude2, longitude2):
    RadiusOfEarth = 6378
    # Haversine formula: https://en.wikipedia.org/wiki/Haversine_formula
    differenceOfLatitudes = toRadians(latitude1) - toRadians(latitude2)
    differenceOfLongitudes = toRadians(longitude1) - toRadians(longitude2)
    s = (math.pow(math.sin(differenceOfLatitudes / 2), 2) + math.cos(toRadians(latitude1))
         * math.cos(toRadians(latitude2)) * math.pow(math.sin(differenceOfLongitudes / 2), 2))
    distanceBetween2Points = 2 * RadiusOfEarth * math.asin(math.sqrt(s))
    return distanceBetween2Points 
Example 59
Project: SherpaHighLevel   Author: Shedino   File: rotmat.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def to_euler(self):
        '''find Euler angles for the matrix'''
        if self.c.x >= 1.0:
            pitch = pi
        elif self.c.x <= -1.0:
            pitch = -pi
        else:
            pitch = -asin(self.c.x)
        roll = atan2(self.c.y, self.c.z)
        yaw  = atan2(self.b.x, self.a.x)
        return (roll, pitch, yaw) 
Example 60
Project: SherpaHighLevel   Author: Shedino   File: mavextra.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def pitch_sim(SIMSTATE, GPS_RAW):
    '''estimate pitch from SIMSTATE accels'''
    xacc = SIMSTATE.xacc - lowpass(delta(GPS_RAW.v,"v")*6.6, "v", 0.9)
    zacc = SIMSTATE.zacc
    zacc += SIMSTATE.ygyro * GPS_RAW.v;
    if xacc/zacc >= 1:
        return 0
    if xacc/zacc <= -1:
        return -0
    return degrees(-asin(xacc/zacc)) 
Example 61
Project: SherpaHighLevel   Author: Shedino   File: mavextra.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def gps_newpos(lat, lon, bearing, distance):
	'''extrapolate latitude/longitude given a heading and distance
	thanks to http://www.movable-type.co.uk/scripts/latlong.html
	'''
        import math
	lat1 = math.radians(lat)
	lon1 = math.radians(lon)
	brng = math.radians(bearing)
	dr = distance/radius_of_earth

	lat2 = math.asin(math.sin(lat1)*math.cos(dr) +
                         math.cos(lat1)*math.sin(dr)*math.cos(brng))
	lon2 = lon1 + math.atan2(math.sin(brng)*math.sin(dr)*math.cos(lat1), 
                                 math.cos(dr)-math.sin(lat1)*math.sin(lat2))
	return (math.degrees(lat2), wrap_valid_longitude(math.degrees(lon2))) 
Example 62
Project: SherpaHighLevel   Author: Shedino   File: mavextra.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def pitch_sim(SIMSTATE, GPS_RAW):
    '''estimate pitch from SIMSTATE accels'''
    xacc = SIMSTATE.xacc - lowpass(delta(GPS_RAW.v,"v")*6.6, "v", 0.9)
    zacc = SIMSTATE.zacc
    zacc += SIMSTATE.ygyro * GPS_RAW.v;
    if xacc/zacc >= 1:
        return 0
    if xacc/zacc <= -1:
        return -0
    return degrees(-asin(xacc/zacc)) 
Example 63
Project: SherpaHighLevel   Author: Shedino   File: mavextra.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def gps_newpos(lat, lon, bearing, distance):
	'''extrapolate latitude/longitude given a heading and distance
	thanks to http://www.movable-type.co.uk/scripts/latlong.html
	'''
        import math
	lat1 = math.radians(lat)
	lon1 = math.radians(lon)
	brng = math.radians(bearing)
	dr = distance/radius_of_earth

	lat2 = math.asin(math.sin(lat1)*math.cos(dr) +
                         math.cos(lat1)*math.sin(dr)*math.cos(brng))
	lon2 = lon1 + math.atan2(math.sin(brng)*math.sin(dr)*math.cos(lat1), 
                                 math.cos(dr)-math.sin(lat1)*math.sin(lat2))
	return (math.degrees(lat2), wrap_valid_longitude(math.degrees(lon2))) 
Example 64
Project: SherpaHighLevel   Author: Shedino   File: rotmat.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def to_euler(self):
        '''find Euler angles for the matrix'''
        if self.c.x >= 1.0:
            pitch = pi
        elif self.c.x <= -1.0:
            pitch = -pi
        else:
            pitch = -asin(self.c.x)
        roll = atan2(self.c.y, self.c.z)
        yaw  = atan2(self.b.x, self.a.x)
        return (roll, pitch, yaw) 
Example 65
Project: PyFluxPro   Author: OzFlux   File: pysolar.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def GetAltitudeFast(latitude_deg, longitude_deg, utc_datetime):

# expect 19 degrees for solar.GetAltitude(42.364908,-71.112828,datetime.datetime(2007, 2, 18, 20, 13, 1, 130320))

        day = GetDayOfYear(utc_datetime)
        declination_rad = math.radians(GetDeclination(day))
        latitude_rad = math.radians(latitude_deg)
        hour_angle = GetHourAngle(utc_datetime, longitude_deg)

        first_term = math.cos(latitude_rad) * math.cos(declination_rad) * math.cos(math.radians(hour_angle))
        second_term = math.sin(latitude_rad) * math.sin(declination_rad)
        return math.degrees(math.asin(first_term + second_term)) 
Example 66
Project: PyFluxPro   Author: OzFlux   File: pysolar.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def GetAzimuthFast(latitude_deg, longitude_deg, utc_datetime):
# expect -50 degrees for solar.GetAzimuth(42.364908,-71.112828,datetime.datetime(2007, 2, 18, 20, 18, 0, 0))
        day = GetDayOfYear(utc_datetime)
        declination_rad = math.radians(GetDeclination(day))
        latitude_rad = math.radians(latitude_deg)
        hour_angle_rad = math.radians(GetHourAngle(utc_datetime, longitude_deg))
        altitude_rad = math.radians(GetAltitude(latitude_deg, longitude_deg, utc_datetime))

        azimuth_rad = math.asin(math.cos(declination_rad) * math.sin(hour_angle_rad) / math.cos(altitude_rad))

        if(math.cos(hour_angle_rad) >= (math.tan(declination_rad) / math.tan(latitude_rad))):
                return math.degrees(azimuth_rad)
        else:
                return (180 - math.degrees(azimuth_rad)) 
Example 67
Project: PyFluxPro   Author: OzFlux   File: pysolar.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def GetGeocentricSunDeclination(apparent_sun_longitude, true_ecliptic_obliquity, geocentric_latitude):
        apparent_sun_longitude_rad = math.radians(apparent_sun_longitude)
        true_ecliptic_obliquity_rad = math.radians(true_ecliptic_obliquity)
        geocentric_latitude_rad = math.radians(geocentric_latitude)

        a = math.sin(geocentric_latitude_rad) * math.cos(true_ecliptic_obliquity_rad)
        b = math.cos(geocentric_latitude_rad) * math.sin(true_ecliptic_obliquity_rad) * math.sin(apparent_sun_longitude_rad)
        delta = math.asin(a + b)
        return math.degrees(delta) 
Example 68
Project: PyFluxPro   Author: OzFlux   File: pysolar.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def GetTopocentricElevationAngle(latitude, topocentric_sun_declination, topocentric_local_hour_angle):
        latitude_rad = math.radians(latitude)
        tsd_rad = math.radians(topocentric_sun_declination)
        tlha_rad = math.radians(topocentric_local_hour_angle)
        return math.degrees(math.asin((math.sin(latitude_rad) * math.sin(tsd_rad)) + math.cos(latitude_rad) * math.cos(tsd_rad) * math.cos(tlha_rad))) 
Example 69
Project: GAfilters   Author: RenataKh   File: graph_builder.py    MIT License 5 votes vote down vote up
def get_phi_theta(x, y, radius, atan_of_radius, phi_i, theta_i):
    phi = math.asin(math.cos(atan_of_radius) * math.sin(phi_i) + y / radius * math.sin(atan_of_radius) * math.cos(phi_i))
    theta = theta_i + math.atan(x * math.sin(atan_of_radius) / (radius * math.cos(phi_i) * math.cos(atan_of_radius) 
                                                                 + y * math.sin(phi_i) * math.sin(atan_of_radius) + 1e-10))
    
    for shift in [0., 1., -1.]:
        xn, yn = phitheta2xy(phi, theta + shift * math.pi, phi_i, theta_i)
        if (((xn - x)**2 < 1e-10) and ((yn - y)**2 < 1e-10)):
            theta = theta + shift * math.pi
            break
    
    return phi, theta 
Example 70
Project: ironpython2   Author: IronLanguages   File: test_math.py    Apache License 2.0 5 votes vote down vote up
def testAsin(self):
        self.assertRaises(TypeError, math.asin)
        self.ftest('asin(-1)', math.asin(-1), -math.pi/2)
        self.ftest('asin(0)', math.asin(0), 0)
        self.ftest('asin(1)', math.asin(1), math.pi/2)
        self.assertRaises(ValueError, math.asin, INF)
        self.assertRaises(ValueError, math.asin, NINF)
        self.assertTrue(math.isnan(math.asin(NAN))) 
Example 71
Project: fairtest   Author: columbia   File: distance.py    Apache License 2.0 5 votes vote down vote up
def haversine(lon1, lat1, lon2, lat2):
    """
    Calculate the great circle distance between two points 
    on the earth (specified in decimal degrees)
    """
    # convert decimal degrees to radians 
    lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])

    # haversine formula 
    dlon = lon2 - lon1 
    dlat = lat2 - lat1 
    a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
    c = 2 * asin(sqrt(a)) 
    r = 3956 # Radius of earth in kilometers. Use 3956 for miles 6371 for km
    return c * r 
Example 72
Project: LipReading   Author: joseph-zhong   File: estimate_pose.py    MIT License 5 votes vote down vote up
def matrix2angle(R):
    ''' compute three Euler angles from a Rotation Matrix. Ref: http://www.gregslabaugh.net/publications/euler.pdf
    Args:
        R: (3,3). rotation matrix
    Returns:
        x: yaw
        y: pitch
        z: roll
    '''
    # assert(isRotationMatrix(R))

    if R[2,0] !=1 or R[2,0] != -1:
        x = asin(R[2,0])
        y = atan2(R[2,1]/cos(x), R[2,2]/cos(x))
        z = atan2(R[1,0]/cos(x), R[0,0]/cos(x))
        
    else:# Gimbal lock
        z = 0 #can be anything
        if R[2,0] == -1:
            x = np.pi/2
            y = z + atan2(R[0,1], R[0,2])
        else:
            x = -np.pi/2
            y = -z + atan2(-R[0,1], -R[0,2])

    return x, y, z 
Example 73
Project: centerpose   Author: tensorboy   File: estimate_pose.py    MIT License 5 votes vote down vote up
def matrix2angle(R):
    ''' compute three Euler angles from a Rotation Matrix. Ref: http://www.gregslabaugh.net/publications/euler.pdf
    Args:
        R: (3,3). rotation matrix
    Returns:
        x: yaw
        y: pitch
        z: roll
    '''
    # assert(isRotationMatrix(R))

    if R[2, 0] != 1 or R[2, 0] != -1:
        x = asin(R[2, 0])
        y = atan2(R[2, 1] / cos(x), R[2, 2] / cos(x))
        z = atan2(R[1, 0] / cos(x), R[0, 0] / cos(x))

    else:  # Gimbal lock
        z = 0  # can be anything
        if R[2, 0] == -1:
            x = np.pi / 2
            y = z + atan2(R[0, 1], R[0, 2])
        else:
            x = -np.pi / 2
            y = -z + atan2(-R[0, 1], -R[0, 2])

    return x, y, z 
Example 74
Project: codecad   Author: bluecube   File: simple2d.py    GNU General Public License v3.0 5 votes vote down vote up
def calculate_n(r, side_length):
        """ Calculate n that would make given radius and side_length work.

        Note that this will typically not be an integer and must be appropriately
        rounded before use. """
        return math.pi / math.asin(side_length / (2 * r)) 
Example 75
Project: ems   Author: mtils   File: geocoordinate.py    MIT License 4 votes vote down vote up
def distanceTo(self, other):
        '''
        Returns the distance (in meters) from this coordinate to the coordinate
        specified by other. Altitude is not used in the calculation.
    
        This calculation returns the great-circle distance between the two
        coordinates, with an assumption that the Earth is spherical for the
        purpose of this calculation.
    
        Returns 0 if the type of this coordinate or the type of \a other is
        QGeoCoordinate::InvalidCoordinate.
        
        @param other: Other GeoCoordinate
        @type other: GeoCoordinate
        @return: float
        '''
        if (self.type_() == self.InvalidCoordinate) and\
            (other.type_() == self.InvalidCoordinate):
            return 0
        
        if self.projection == "utm":
            xMeters = abs(other.lat - self.lat)
            yMeters = abs(other.lng - self.lng)
            try:
                return math.sqrt((xMeters ** 2) + (yMeters ** 2))
            except ZeroDivisionError:
                return 0.0
            
        #Haversine Formula
        dlat = self.degToRad(other.lat - self.lat)
        dlon = self.degToRad(other.lng - self.lng)
        
        haversine_dlat = math.sin(dlat / 2.0)
        haversine_dlat *= haversine_dlat
        haversine_dlon = math.sin(dlon / 2.0)
        haversine_dlon *= haversine_dlon
        
        y = haversine_dlat\
            + math.cos(self.degToRad(self.lat))\
            * math.cos(self.degToRad(other.lat))\
            * haversine_dlon
        x = 2 * math.asin(math.sqrt(y))
        return float(x * self.EARTH_MEAN_RADIUS * 1000.0) 
Example 76
Project: CAHVOR_camera_model   Author: bvnayak   File: get_photogrammetric_model.py    BSD 2-Clause "Simplified" License 4 votes vote down vote up
def compute_photogrammetric(CAHVOR_model):
    """
    Computation of photogrammetric parameters form CAHVOR.

    Parameters
    ----------
    CAHVOR: dict
        Take dictionary containing CAHVOR model and other parameters such as
        'hs', 'vs', 'hc' and 'vc'.

    Returns:
    photogrammetric: dict
        Returns dict containing computed photogrammetric parameters from
        CAHVOR model. Photogrammetric camera Parameters such as
        'camera center', 'focallength', 'rotation angles', 'rotation matrix',
        'pixel size', 'principal point', 'image size' and 'az' and 'el'
        to get back to origin position of PTU.
    """
    r_matrix = make_rotation_matrix(CAHVOR_model['A'], CAHVOR_model['H'],
                                    CAHVOR_model['V'], CAHVOR_model['hs'],
                                    CAHVOR_model['vs'], CAHVOR_model['hc'],
                                    CAHVOR_model['vc'])
    M = r_matrix
    f = CAHVOR_model['pixel_size'] * CAHVOR_model['hs']

    # camera center
    Xc = CAHVOR_model['C'][0]
    Yc = CAHVOR_model['C'][1]
    Zc = CAHVOR_model['C'][2]

    # angles
    phi = math.asin(r_matrix[2][0])
    w = - math.asin(r_matrix[2][1] / math.cos(phi))
    k = math.acos(r_matrix[0][0] / math.cos(phi))

    w = math.degrees(w)
    phi = math.degrees(phi)
    k = math.degrees(k)

    k0 = CAHVOR_model['R'][0]
    k1 = CAHVOR_model['R'][1] / (f**2)
    k2 = CAHVOR_model['R'][2] / (f**4)

    x0 = CAHVOR_model['pixel_size'] * \
        (CAHVOR_model['hc'] - (CAHVOR_model['imsize'][1] / 2))
    y0 = - CAHVOR_model['pixel_size'] * \
        (CAHVOR_model['vc'] - (CAHVOR_model['imsize'][0] / 2))
    R = compute_rotation_matrix(w, phi, k)

    photogrammetric = dict([('M', M), ('f', f), ('Xc', Xc), ('Yc', Yc),
                            ('Zc', Zc), ('w', w), ('phi', phi), ('k', k),
                            ('k0', k0), ('k1', k1), ('k2', k2), ('x0', x0),
                            ('y0', y0), ('R', R)])
    return photogrammetric 
Example 77
Project: eYSIP_2015_Marker_based_Robot_Localisation   Author: eyantrainternship   File: Client2.py    Creative Commons Zero v1.0 Universal 4 votes vote down vote up
def getProperties(points):
    """
    * Function Name:	getProperties
    * Input:		A set of four points of the corners of aruco markers.
                        These points can be obtained from is_aruco_present()
                        function.
    * Output:		-
    * Logic:		The Perspective-n-Point problem is solved by Ransac
                        algorithm. We obtain the translation and rotation
                        vectors through this function.
    * Example Call:	getProperties(points)
    """

    global objp
    
    # Arrays to store object points and image points from all the images.
    objpoints = objp
    print "OBJP", objpoints
    
    imgpoints = points

    #imgpoints = np.array(imgpoints)
    print "IMGP", imgpoints

    mtx = np.load('matrix.npy')
    dist = np.load('distortion.npy')

    rvec, tvec, inliers = cv2.solvePnPRansac(objpoints, imgpoints, mtx, dist)
    print "Rvec\n", rvec
    print "\nTvec", tvec

    x = tvec[0][0]
    y = tvec[2][0]

    dst, jacobian = cv2.Rodrigues(rvec)

    print "Rot Matrix", dst

    t = math.asin(-dst[0][2])
    t1 = math.acos(dst[0][0])

    return x, y, t, t1 
Example 78
Project: RVO_Py_MAS   Author: MengGuo   File: RVO.py    GNU General Public License v2.0 4 votes vote down vote up
def RVO_update(X, V_des, V_current, ws_model):
    """ compute best velocity given the desired velocity, current velocity and workspace model"""
    ROB_RAD = ws_model['robot_radius']+0.1
    V_opt = list(V_current)    
    for i in range(len(X)):
        vA = [V_current[i][0], V_current[i][1]]
        pA = [X[i][0], X[i][1]]
        RVO_BA_all = []
        for j in range(len(X)):
            if i!=j:
                vB = [V_current[j][0], V_current[j][1]]
                pB = [X[j][0], X[j][1]]
                # use RVO
                transl_vB_vA = [pA[0]+0.5*(vB[0]+vA[0]), pA[1]+0.5*(vB[1]+vA[1])]
                # use VO
                #transl_vB_vA = [pA[0]+vB[0], pA[1]+vB[1]]
                dist_BA = distance(pA, pB)
                theta_BA = atan2(pB[1]-pA[1], pB[0]-pA[0])
                if 2*ROB_RAD > dist_BA:
                    dist_BA = 2*ROB_RAD
                theta_BAort = asin(2*ROB_RAD/dist_BA)
                theta_ort_left = theta_BA+theta_BAort
                bound_left = [cos(theta_ort_left), sin(theta_ort_left)]
                theta_ort_right = theta_BA-theta_BAort
                bound_right = [cos(theta_ort_right), sin(theta_ort_right)]
                # use HRVO
                # dist_dif = distance([0.5*(vB[0]-vA[0]),0.5*(vB[1]-vA[1])],[0,0])
                # transl_vB_vA = [pA[0]+vB[0]+cos(theta_ort_left)*dist_dif, pA[1]+vB[1]+sin(theta_ort_left)*dist_dif]
                RVO_BA = [transl_vB_vA, bound_left, bound_right, dist_BA, 2*ROB_RAD]
                RVO_BA_all.append(RVO_BA)                
        for hole in ws_model['circular_obstacles']:
            # hole = [x, y, rad]
            vB = [0, 0]
            pB = hole[0:2]
            transl_vB_vA = [pA[0]+vB[0], pA[1]+vB[1]]
            dist_BA = distance(pA, pB)
            theta_BA = atan2(pB[1]-pA[1], pB[0]-pA[0])
            # over-approximation of square to circular
            OVER_APPROX_C2S = 1.5
            rad = hole[2]*OVER_APPROX_C2S
            if (rad+ROB_RAD) > dist_BA:
                dist_BA = rad+ROB_RAD
            theta_BAort = asin((rad+ROB_RAD)/dist_BA)
            theta_ort_left = theta_BA+theta_BAort
            bound_left = [cos(theta_ort_left), sin(theta_ort_left)]
            theta_ort_right = theta_BA-theta_BAort
            bound_right = [cos(theta_ort_right), sin(theta_ort_right)]
            RVO_BA = [transl_vB_vA, bound_left, bound_right, dist_BA, rad+ROB_RAD]
            RVO_BA_all.append(RVO_BA)
        vA_post = intersect(pA, V_des[i], RVO_BA_all)
        V_opt[i] = vA_post[:]
    return V_opt 
Example 79
Project: bop_toolkit   Author: thodan   File: view_sampler.py    MIT License 4 votes vote down vote up
def fibonacci_sampling(n_pts, radius=1.0):
  """Samples an odd number of almost equidistant 3D points from the Fibonacci
  lattice on a unit sphere.

  Latitude (elevation) represents the rotation angle around the X axis.
  Longitude (azimuth) represents the rotation angle around the Z axis.

  Ref:
  [1] https://arxiv.org/pdf/0912.4540.pdf
  [2] http://stackoverflow.com/questions/34302938/map-point-to-closest-point-on-fibonacci-lattice
  [3] http://stackoverflow.com/questions/9600801/evenly-distributing-n-points-on-a-sphere
  [4] https://www.openprocessing.org/sketch/41142

  :param n_pts: Number of 3D points to sample (an odd number).
  :param radius: Radius of the sphere.
  :return: List of 3D points on the sphere surface.
  """
  # Needs to be an odd number [1].
  assert (n_pts % 2 == 1)
  n_pts_half = int(n_pts / 2)

  phi = (math.sqrt(5.0) + 1.0) / 2.0  # Golden ratio.
  phi_inv = phi - 1.0
  ga = 2.0 * math.pi * phi_inv  # Complement to the golden angle.

  pts = []
  for i in range(-n_pts_half, n_pts_half + 1):
    lat = math.asin((2 * i) / float(2 * n_pts_half + 1))
    lon = (ga * i) % (2 * math.pi)

    # Convert the latitude and longitude angles to 3D coordinates.
    s = math.cos(lat) * radius
    x, y, z = math.cos(lon) * s, math.sin(lon) * s, math.tan(lat) * s
    pts.append([x, y, z])

    # Calculate rotation matrix and translation vector.
    # Note: lat,lon=0,0 is a camera looking to the sphere center from
    # (-radius, 0, 0) in the world (i.e. sphere) coordinate system.
    # pi_half = 0.5 * math.pi
    # alpha_x = -lat - pi_half
    # alpha_z = lon + pi_half
    # R_x = transform.rotation_matrix(alpha_x, [1, 0, 0])[:3, :3]
    # R_z = transform.rotation_matrix(alpha_z, [0, 0, 1])[:3, :3]
    # R = np.linalg.inv(R_z.dot(R_x))
    # t = -R.dot(np.array([x, y, z]).reshape((3, 1)))

  return pts 
Example 80
Project: Rackman   Author: FRiMN   File: rackman.py    MIT License 4 votes vote down vote up
def resize_window(self, widget):
        dpm = self.get_monitor()
        w, h = self.window.get_size()
        metric_name = self.metric[0]

        if metric_name == 'px':
            metric_mod = 1
            precision_norm = 0
            precision_high = 2
        elif metric_name == 'mm':
            metric_mod = 1.0 / dpm
            precision_norm = 2
            precision_high = 2
        elif metric_name == 'in':
            metric_mod = 1.0 / dpm / 25.4
            precision_norm = 3
            precision_high = 3
        elif metric_name == 'pt (adobe)':
            metric_mod = 1.0 / dpm / 0.352777
            precision_norm = 1
            precision_high = 1
        else:
            raise ValueError( "Unknown metric: {}".format(metric_name) )

        self.metric = (metric_name, metric_mod, precision_norm, precision_high)

        gipo = math.sqrt(h*h + w*w)     # гипотенуза

        grad1 = math.degrees( math.asin( h / gipo ) )
        grad2 = 90 - grad1

        percent_w = ( w * 100.0 / self.percent_full[0] )
        percent_h = ( h * 100.0 / self.percent_full[1] )
        percent_d = ( gipo * 100.0 / ( math.sqrt(self.percent_full[0]*self.percent_full[0] + self.percent_full[1]*self.percent_full[1]) ) )

        if w >= h:
            ratio = float(w) / h
        else:
            ratio = float(h) / w

        r = str( round(ratio, 3) )
        if r in TV_RATIOS.keys():
            ratio_tv = '({})'.format(TV_RATIOS[r])
        else:
            ratio_tv = ''

        T = Template('{:.${precision}f}{:s}')
        norm = T.substitute(precision=precision_norm)
        high = T.substitute(precision=precision_high)

        self.parent.vw.set_text( norm.format( round(w       * metric_mod, precision_norm), metric_name.split()[0] ) )
        self.parent.vh.set_text( norm.format( round(h       * metric_mod, precision_norm), metric_name.split()[0] ) )
        self.parent.vd.set_text( high.format( round(gipo    * metric_mod, precision_high), metric_name.split()[0] ) )
        self.parent.va.set_text( '{:.1f}° / {:.1f}°'.format( round(grad1,1), round(grad2,1) ) )

        self.parent.vpr.set_text( '{:.2f}% x {:.2f}% / {:.2f}%'.format( percent_w, percent_h, percent_d ) )
        self.parent.var.set_text( '{:.3f}:1 {:s}'.format( ratio, ratio_tv ) )

        return True