Python haversine.haversine() Examples

The following are 19 code examples of haversine.haversine(). 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 haversine , or try the search function .
Example #1
Source File: environment.py    From cti-python-stix2 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def partial_location_distance(lat1, long1, lat2, long2, threshold):
    """Given two coordinates perform a matching based on its distance using the Haversine Formula.

    Args:
        lat1: Latitude value for first coordinate point.
        lat2: Latitude value for second coordinate point.
        long1: Longitude value for first coordinate point.
        long2: Longitude value for second coordinate point.
        threshold (float): A kilometer measurement for the threshold distance between these two points.

    Returns:
        float: Number between 0.0 and 1.0 depending on match.

    """
    from haversine import haversine, Unit
    distance = haversine((lat1, long1), (lat2, long2), unit=Unit.KILOMETERS)
    result = 1 - (distance / threshold)
    logger.debug(
        "--\t\tpartial_location_distance '%s' '%s' threshold: '%s'\tresult: '%s'",
        (lat1, long1), (lat2, long2), threshold, result,
    )
    return result


# default weights used for the semantic equivalence process 
Example #2
Source File: tsp_ga.py    From TSP-GA with MIT License 6 votes vote down vote up
def get_distance_to(self, dest):
        origin = (self.lat, self.lng)
        dest = (dest.lat, dest.lng)

        forward_key = origin + dest
        backward_key = dest + origin

        if forward_key in Gene.__distances_table:
            return Gene.__distances_table[forward_key]

        if backward_key in Gene.__distances_table:
            return Gene.__distances_table[backward_key]

        dist = int(haversine(origin, dest))
        Gene.__distances_table[forward_key] = dist

        return dist 
Example #3
Source File: utils.py    From geoinference with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def location_error(true_loc, coord, LocRes):
	# we create location resolver in method.py because we don't want it to load every time we import this file
	if not true_loc: return 0.0
	# check if location field contains coordinates
	#coord = isCoord(text_loc)
	if coord: return haversine(true_loc, coord)
	# resolve to lat lon 
	res = LocRes.reverse_geocode(text_loc.split()[0],text_loc.split()[1])
	if not res: return 0.0
	res_val = map(float, res)
	return haversine(true_loc, res_val)

# create a vector 
# [ mention relationship, location error, post data, social triangles ] 
Example #4
Source File: dijkstra.py    From dijkstra with Apache License 2.0 5 votes vote down vote up
def get_price(origin, destination, cents_per_km=0.1):
        """Return the cheapest flight without stops."""

        # Haversine distance, in kilometers
        point1 = origin.latitude, origin.longitude,
        point2 = destination.latitude, destination.longitude
        distance = haversine.haversine(point1, point2)
        return distance * cents_per_km 
Example #5
Source File: polyline_generator.py    From PokemonGo-Bot-Backup with MIT License 5 votes vote down vote up
def get_total_distance(self):
        return math.ceil(sum([haversine.haversine(*x) * 1000 for x in self._get_walk_steps()])) 
Example #6
Source File: polyline_generator.py    From PokemonGo-Bot-Backup with MIT License 5 votes vote down vote up
def get_pos(self):
        if self.speed > self.get_total_distance():
            self._last_pos = self.destination
            self._last_step = len(self._step_keys)-1
        if self.get_last_pos() == self.destination:
            return self.get_last_pos()
        distance = self.speed
        origin = Point(*self._last_pos)
        ((so_lat, so_lng), (sd_lat, sd_lng)) = self._step_dict[self._step_keys[self._last_step]]
        bearing = self._calc_bearing(so_lat, so_lng, sd_lat, sd_lng)
        while haversine.haversine(self._last_pos, (sd_lat, sd_lng))*1000 < distance:
            distance -= haversine.haversine(self._last_pos, (sd_lat, sd_lng))*1000
            self._last_pos = (sd_lat, sd_lng)
            if self._last_step < len(self._step_keys)-1:
                self._last_step += 1
                ((so_lat, so_lng), (sd_lat, sd_lng)) = self._step_dict[self._step_keys[self._last_step]]
                bearing = self._calc_bearing(so_lat, so_lng, sd_lat, sd_lng)
                origin = Point(so_lat, so_lng)
                lat, lng = self._calc_next_pos(origin, distance, bearing)
                if haversine.haversine(self._last_pos, (lat, lng))*1000 < distance:
                    distance -= haversine.haversine(self._last_pos, (lat, lng))*1000
                    self._last_pos = (lat, lng)
            else:
                return self.get_last_pos()
        else:
            lat, lng = self._calc_next_pos(origin, distance, bearing)
            self._last_pos = (lat, lng)
            return self.get_last_pos() 
Example #7
Source File: polyline_generator.py    From PokemonGo-Bot-Backup with MIT License 5 votes vote down vote up
def get_alt(self):
        closest_sample = None
        best_distance = float("inf")
        for point in self._elevation_at_point.keys():
            local_distance = haversine.haversine(self._last_pos, point)*1000
            if local_distance < best_distance:
                closest_sample = point
                best_distance = local_distance
        if closest_sample in self._elevation_at_point:
            return self._elevation_at_point[closest_sample]
        else:
            return None 
Example #8
Source File: polyline_generator.py    From PokemonGo-Bot-Backup with MIT License 5 votes vote down vote up
def _get_steps_dict(self):
        walked_distance = 0.0
        steps_dict = {}
        for step in self._get_walk_steps():
            walked_distance += haversine.haversine(*step) * 1000
            steps_dict[walked_distance] = step
        return steps_dict 
Example #9
Source File: polyline_generator.py    From PokemonGo-Bot-Backup with MIT License 5 votes vote down vote up
def cached_polyline(origin, destination, speed, google_map_api_key=None):
        '''
        Google API has limits, so we can't generate new Polyline at every tick...
        '''

        # Absolute offset between bot origin and PolyLine get_last_pos() (in meters)
        if PolylineObjectHandler._cache and PolylineObjectHandler._cache.get_last_pos() != (None, None):
            abs_offset = haversine.haversine(tuple(origin), PolylineObjectHandler._cache.get_last_pos())*1000
        else:
            abs_offset = float("inf")
        is_old_cache = lambda : abs_offset > 8 # Consider cache old if we identified an offset more then 8 m
        new_dest_set = lambda : tuple(destination) != PolylineObjectHandler._cache.destination

        if PolylineObjectHandler._run and (not is_old_cache()):
            # bot used to have struggle with making a decision.
            PolylineObjectHandler._instability -= 1
            if PolylineObjectHandler._instability <= 0:
                PolylineObjectHandler._instability = 0
                PolylineObjectHandler._run = False
            pass # use current cache
        elif None == PolylineObjectHandler._cache or is_old_cache() or new_dest_set():
            # no cache, old cache or new destination set by bot, so make new polyline
            PolylineObjectHandler._instability += 2
            if 10 <= PolylineObjectHandler._instability:
                PolylineObjectHandler._run = True
                PolylineObjectHandler._instability = 20 # next N moves use same cache

            PolylineObjectHandler._cache = Polyline(origin, destination, speed, google_map_api_key)
        else:
            # valid cache found
            PolylineObjectHandler._instability -= 1
            PolylineObjectHandler._instability = max(PolylineObjectHandler._instability, 0)
            pass # use current cache
        return PolylineObjectHandler._cache 
Example #10
Source File: tile.py    From MobikeAgent with MIT License 5 votes vote down vote up
def max_side(self):  # unit: m
        return max(haversine((self.lon_min, self.lat_min), (self.lon_min, self.lat_max)),
                   haversine((self.lon_min, self.lat_min), (self.lon_max, self.lat_min)),
                   haversine((self.lon_min, self.lat_max), (self.lon_max, self.lat_max))) * 1000 
Example #11
Source File: utils.py    From geoinference with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def distance(loc1, loc2):
	if loc1 == None or loc2 == None:
		return -1
	return haversine(loc1, loc2, miles=True)

# get random coordinates 
Example #12
Source File: method.py    From geoinference with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def calculate_probability(self, l_u, l_v):
        """
        Calculates the probability of the edge being present given the distance
        between user u and neighbor v, l_u indicates the location of user u and
        l_v indicates the location of user v (tuples containing latitude and
        longitude).
        """
        return self.a * (abs(haversine(l_u,l_v,miles=True)) + self.b)**(self.c) 
Example #13
Source File: method.py    From geoinference with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def most_likely_location(self,user,location_set):
        """
        Returns the most likely location for a user of unknown locale,
        based on the social tightness model.
        """
        max_probability = float('-inf')
        best_location = None
        for neighbor_u in self.mention_network.neighbors_iter_(user):
            if neighbor_u not in location_set: continue

            location_of_neighbor_u = self.mention_network.node_data_(neighbor_u)
            probability = 0

            for neighbor_v in self.mention_network.neighbors_iter_(neighbor_u):
                if neighbor_v not in location_set: continue
                location_of_neighbor_v = self.mention_network.node_data_(neighbor_v)

                #to get the dict-lookup correct, we round to the nearest kilometer
                distance = round(haversine(location_of_neighbor_u,location_of_neighbor_v),0)

                # "" , round to two significant figures
                social_closeness = self.sij[neighbor_u][neighbor_v]
                probability += self.probability_distance_social_closeness[distance][social_closeness]

            #compare the probability of this neighbor with other possible neighbors
            #sets the highest-probability user as the most likely location
            if probability > max_probability:
                max_probability = probability
                best_location = location_of_neighbor_u
    
        return best_location 
Example #14
Source File: method.py    From geoinference with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def social_closeness(self):
        """
        The social tightness based model is based on the assumption
        that different friends hae different importance to a user.
        The social closeness between two users is measured via cosine similarly,
        then we estimate the probability of user i and user j located at a distance
        | l_i - l_j | with social closeness. Then we estimate the probability of user_i
        located at l_i and use the location with the top probability
        """
        pairs = 0
        #here we calculate social closeness
        logger.debug("Calcuating social closeness")
        for user in self.users_with_location:
            user_location = self.mention_network.node_data_(user)
            for friend in self.mention_network.neighbors_iter_(user):
                friend_location = self.mention_network.node_data_(friend)
                if not friend_location: continue

                pairs += 1
                social_closeness = round(self.cosine_similarity(user,friend),2)
                self.sij[user][friend] = social_closeness
                distance = round(haversine(user_location,friend_location),0)
                self.probability_distance_social_closeness[distance][social_closeness] += 1.0

        #the normalizing factor is the total number of social_closeness probabilities added above...
        normalizing_factor = pairs
        for distance in self.probability_distance_social_closeness:
            for social_closeness in self.probability_distance_social_closeness[distance]:
                self.probability_distance_social_closeness[distance][social_closeness] /= normalizing_factor
        logger.debug("Finished calculating the social closeness...") 
Example #15
Source File: method.py    From geoinference with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_geometric_mean(self, locations):
        """
        Locates the geometric mean of a list of locations, taken from David Jurgen's implementation,
        with less than three locations a random location is selected, else construct a geometric mean.
        """

        n = len(locations)

        # The geometric median is only defined for n > 2 points, so just return
        # an arbitrary point if we have fewer
        if n < 2:
            return locations[np.random.randint(0, n)]

        min_distance_sum = 10000000
        median = None  # Point type

        # Loop through all the points, finding the point that minimizes the
        # geodetic distance to all other points.  By construction median will
        # always be assigned to some non-None value by the end of the loop.
        for i in range(0, n):
            p1 = locations[i]
            dist_sum = 0
            for j in range(0, n):
                p2 = locations[j]
                # Skip self-comparison
                if i == j:
                    continue
                dist = haversine(p1, p2)
                dist_sum += dist

                # Short-circuit early if it's clear that this point cannot be
                # the median since it does not minimize the distance sum
                if dist_sum > min_distance_sum:
                    break

            if dist_sum < min_distance_sum:
                min_distance_sum = dist_sum
                median = p1

        return median 
Example #16
Source File: GPS_VO.py    From visual_odometry with MIT License 5 votes vote down vote up
def getGPS_distance(prevGPS, curGPS):
    """ Returns the distance between two GPS coordinates(in Lat/Lon Coord System) in meters"""
    distance = haversine.haversine(prevGPS, curGPS) * 1000  # meters

    return distance 
Example #17
Source File: TrajectoryAnalytics.py    From Predicting-Transportation-Modes-of-GPS-Trajectories with Apache License 2.0 4 votes vote down vote up
def calculatePointFeatures(self):
        '''
        Here we are calculating distance, speed, acceleration and bearing.

        Filtering the data so as to remove as per our preprocessed data and understanding of trajectories.
        We are filtering:-
        1. The information if starting inf is from 1 user and ending inf is from another user
        2. The information if starting inf is from 1 transportation mode and ending inf is from another transportation mode
        3. If the starting date and ending date match or not
        '''

        FMT = '%H:%M:%S'
        filteredData = [item for item in self.dataList
                        if item[0] == item[10] and item[1] == item[11] and item[2] == item[8]]

        # Here we are creating a flag numerical column so as to easily find when there is a change in subtrajectory or trajectory
        startId = filteredData[0][0]
        startMode = filteredData[0][1]
        startDate = filteredData[0][2]
        subTrajGrper = []
        count = 1
        for row in filteredData:
            if (startId == row[0] and startMode == row[1] and startDate == row[2]):
                subTrajGrper.append(count)
            else:
                startId = row[0]
                startMode = row[1]
                startDate = row[2]
                count += 1
                subTrajGrper.append(count)
        # Calculating Distance
        distance = [haversine((float(row[4]), float(row[5])), (float(row[6]), float(row[7]))) * 1000.0 for row in
                    filteredData]
        # Calculating Time
        time = [(datetime.strptime(str(row[9]), FMT) - datetime.strptime(str(row[3]), FMT)).seconds for row in
                filteredData]
        # Calculating speed
        speed = [x / y if y != 0 else 0 for x, y in zip(distance, time)]
        # Calculating acceleration
        pairedSpeed = list(Utils.pairwise(speed))
        acceleration = [(x[1] - x[0]) / y if (y != 0 and x[1] != None) else 0 for x, y in zip(pairedSpeed, time)]
        # Calculating Bearing
        bearing = [Utils.bearing_Calculator(row) for row in filteredData]

        # Here we are doing a list compression so as to add the answer of Q1 to our preprocessed data.
        dataA1Soln = [u + [v, w, x, y, z] for u, v, w, x, y, z in
                      zip(filteredData, subTrajGrper, distance, speed, acceleration, bearing)]

        # Here we are masking the accleration to 0 in case it is calculated by change in speed between 2 different users.
        pairedA1 = list(Utils.pairwise(dataA1Soln))
        self.dataA1Soln = [list(map(mul, rows[0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1])) if (
                    rows[1] != None and rows[0][12] != rows[1][12]) else rows[0] for rows in pairedA1]
        return dataA1Soln 
Example #18
Source File: method.py    From geoinference with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def following_model(self, user):
        """
        If mu = 0, we decide whether there is f<i,j> based on the location-based following model as shown
        in eq. 1
        """
        #(note: this is almost the same as the Backstrom paper, thus I'll ignore generating
        #the theta values and just calculate max probability)
        def calculate_probability(l_u, l_v):
            """
            Calculates the probability, P(f<i,j>|alpha,beta,location_1,location_2)
            """
            try:
                return self.beta * (abs(haversine(l_u, l_v))) ** (self.alpha)
            except:
                #this needs to be changed to a very small value....
                return self.beta * (0.00000001) ** self.alpha

        best_log_probability = float('-inf')
        best_location = None
        for neighbor_u in self.mention_network.neighbors_iter(user):
            log_probability = 0
            if neighbor_u not in self.u_star:
                continue
            for neighbor_v in self.mention_network.neighbors_iter(neighbor_u):
                if neighbor_v not in self.u_star:
                    continue
                else:
                    l_u = self.mention_network.node_data(neighbor_u)
                    l_v = self.mention_network.node_data(neighbor_v)
                    plu_lv = calculate_probability(l_u, l_v)
                    try:
                        log_gamma_lu = math.log((plu_lv / (1 - plu_lv)))
                    except ValueError:
                        #in the case where l_u == l_v, then plu_lv --> 0 and log(1) = 0,
                        #thus this exception should be valid.
                        log_gamma_lu = 0
                    log_probability += log_gamma_lu
            if log_probability > best_log_probability:
                best_log_probability = log_probability
                best_location = self.mention_network.node_data(neighbor_u)
        if best_location:
            self.user_multi_locations[user].append(best_location)
        return 
Example #19
Source File: method.py    From geoinference with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def compute_coefficients(self):
        """
        Computes the coefficients for equation (1) form the paper,
        P(f<i,j>|alpha,beta,x_i,y_i) = beta*distance(x_i,y_i)^alpha
        """

        def func_to_fit(x, a, b):
                return b * x ** a

        mentions_per_distance = Counter()
        following_relationship = Counter()

        # our networks are too large to generate these coefficients on each call...
        # this is about the same number of combinations as shown in the paper...
        n = 10000000
        #random_sample = random.sample(list(self.u_star),n)
        random_sample = list(self.u_star)
        number_of_users = len(self.u_star)

        # processed_combinations = 0
        # start_time = time.time()
        #for node_u, node_v in combinations(random_sample,2):
        for i in range(0,n):
            node_u, node_v = (random_sample[random.randint(0,number_of_users-1)],random_sample[random.randint(0,number_of_users-1)])
            if node_u == node_v: continue
            # if processed_combinations % 1000000 == 0:
            #     logger.debug("Took %f to process %d combinations..." % ((time.time() - start_time), processed_combinations))
            # processed_combinations += 1
            l_u = self.mention_network.node_data(node_u)
            l_v = self.mention_network.node_data(node_v)
            distance = round(haversine(l_u,l_v,miles=True),0)
            if distance > 10000:
                continue
            mentions_per_distance[distance] += 1.0
            self.N_squared += 1.0
            if self.mention_network.has_edge(node_u,node_v):
                following_relationship[distance] += 1.0
                self.S += 1.0

        x = list(sorted([key for key in mentions_per_distance]))
        x[0] += 1e-8
        y = []
        for key in mentions_per_distance:
            # "ratio of the number of pairs that have following relationship to the total number of pairs in the d_th bucket"
            mentions = mentions_per_distance[key]
            if mentions == 0:
                x.remove(key)
                continue
            following = following_relationship[key]
            ratio = following/mentions
            y.append(ratio)

        solutions = curve_fit(func_to_fit, x, y,p0=[-0.55,0.0045], maxfev=100000)[0]

        self.alpha = solutions[0]
        self.beta = solutions[1]
        return