Python geopy.distance.great_circle() Examples

The following are 11 code examples of geopy.distance.great_circle(). 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 geopy.distance , or try the search function .
Example #1
Source File: pokemon_hunter.py    From PokemonGo-Bot with MIT License 6 votes vote down vote up
def get_search_points(self, cell_id):
        points = []

        # For cell level 15
        for c in Cell(CellId(cell_id)).subdivide():
            for cc in c.subdivide():
                latlng = LatLng.from_point(cc.get_center())
                point = (latlng.lat().degrees, latlng.lng().degrees)
                points.append(point)

        points[0], points[1] = points[1], points[0]
        points[14], points[15] = points[15], points[14]
        point = points.pop(2)
        points.insert(7, point)
        point = points.pop(13)
        points.insert(8, point)

        closest = min(points, key=lambda p: great_circle(self.bot.position, p).meters)
        index = points.index(closest)

        return points[index:] + points[:index] 
Example #2
Source File: test_pgeocode.py    From pgeocode with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_haversine_distance():
    try:
        from geopy.distance import great_circle
    except ImportError:
        raise pytest.skip("scikit-learn not installed")

    rng = np.random.RandomState(42)

    N = 100

    x = rng.rand(N, 2) * 80
    y = x * rng.rand(N, 2)

    d_ref = np.zeros(N)
    for idx, (x_coord, y_coord) in enumerate(zip(x, y)):
        d_ref[idx] = great_circle(x_coord, y_coord).km

    d_pred = haversine_distance(x, y)
    # same distance +/- 3 km
    assert_allclose(d_ref, d_pred, atol=3) 
Example #3
Source File: polyline_generator.py    From PokemonGo-Bot with MIT License 5 votes vote down vote up
def get_alt(self, at_point=None):
        if at_point is None:
            at_point = self._last_pos
        if self._elevation_at_point:
            elevations = sorted([(great_circle(at_point, k).meters, v, k) for k, v in self._elevation_at_point.items()])

            if len(elevations) == 1:
                return elevations[0][1]
            else:
                (distance_to_p1, ep1, p1), (distance_to_p2, ep2, p2) = elevations[:2]
                distance_p1_p2 = great_circle(p1, p2).meters
                return self._get_relative_hight(ep1, ep2, distance_p1_p2, distance_to_p1, distance_to_p2)
        else:
            return None 
Example #4
Source File: camp_fort.py    From PokemonGo-Bot with MIT License 5 votes vote down vote up
def update_cluster_distance(self, cluster):
        cluster["distance"] = great_circle(self.bot.position, cluster["center"]).meters 
Example #5
Source File: camp_fort.py    From PokemonGo-Bot with MIT License 5 votes vote down vote up
def get_distance(self, location, fort):
        return great_circle(location, (fort["latitude"], fort["longitude"])).meters 
Example #6
Source File: pokemon_hunter.py    From PokemonGo-Bot with MIT License 5 votes vote down vote up
def get_distance(self, location, pokemon):
        return great_circle(location, (pokemon["latitude"], pokemon["longitude"])).meters 
Example #7
Source File: preprocessing.py    From Geocoding-with-Map-Vector with GNU General Public License v3.0 5 votes vote down vote up
def populate_sql():
    """
    Create and populate the sqlite3 database with GeoNames data. Requires Geonames dump.
    No need to run this function, I share the database as a separate dump on GitHub (see link).
    """
    geo_names = {}
    p_map = {"PPLC": 100000, "PCLI": 100000, "PCL": 100000, "PCLS": 10000, "PCLF": 10000, "CONT": 100000, "RGN": 100000}

    for line in codecs.open(u"../data/allCountries.txt", u"r", encoding=u"utf-8"):
        line = line.split("\t")
        feat_code = line[7]
        class_code = line[6]
        pop = int(line[14])
        for name in [line[1], line[2]] + line[3].split(","):
            name = name.lower()
            if len(name) != 0:
                if name in geo_names:
                    already_have_entry = False
                    for item in geo_names[name]:
                        if great_circle((float(line[4]), float(line[5])), (item[0], item[1])).km < 100:
                            if item[2] >= pop:
                                already_have_entry = True
                    if not already_have_entry:
                        pop = get_population(class_code, feat_code, p_map, pop)
                        geo_names[name].add((float(line[4]), float(line[5]), pop, feat_code))
                else:
                    pop = get_population(class_code, feat_code, p_map, pop)
                    geo_names[name] = {(float(line[4]), float(line[5]), pop, feat_code)}

    conn = sqlite3.connect(u'../data/geonames.db')
    c = conn.cursor()
    # c.execute("CREATE TABLE GEO (NAME VARCHAR(100) PRIMARY KEY NOT NULL, METADATA VARCHAR(5000) NOT NULL);")
    c.execute(u"DELETE FROM GEO")  # alternatively, delete the database file.
    conn.commit()

    for gn in geo_names:
        c.execute(u"INSERT INTO GEO VALUES (?, ?)", (gn, str(list(geo_names[gn]))))
    print(u"Entries saved:", len(geo_names))
    conn.commit()
    conn.close() 
Example #8
Source File: station.py    From avwx-engine with MIT License 5 votes vote down vote up
def distance(self, lat: float, lon: float) -> Distance:
        """
        Returns a geopy Distance using the great circle method
        """
        return great_circle((lat, lon), (self.latitude, self.longitude)) 
Example #9
Source File: geoname_annotator.py    From EpiTator with Apache License 2.0 5 votes vote down vote up
def set_contextual_features(self):
        """
        GeonameFeatures are initialized with only values that can be extracted
        from the geoname database and span. This extends the GeonameFeature
        with values that require information from nearby_mentions.
        """
        geoname = self.geoname
        close_locations = 0
        very_close_locations = 0
        containing_locations = 0
        contained_locations = 0
        for recently_mentioned_geoname in self.nearby_mentions:
            if recently_mentioned_geoname == geoname:
                continue
            if location_contains(recently_mentioned_geoname, geoname) > 0:
                containing_locations += 1
            if location_contains(geoname, recently_mentioned_geoname) > 0:
                contained_locations += 1
            distance = great_circle(
                recently_mentioned_geoname.lat_long, geoname.lat_long
            ).kilometers
            if distance < 400:
                close_locations += 1
            if distance < 100:
                very_close_locations += 1
        greatest_overlapping_score = 0.0
        for location in geoname.overlapping_locations:
            if location.base_score > greatest_overlapping_score:
                greatest_overlapping_score = location.base_score
        self.set_values(dict(
            close_locations=close_locations,
            very_close_locations=very_close_locations,
            base_score=geoname.base_score,
            base_score_margin=geoname.base_score - greatest_overlapping_score,
            containing_locations=containing_locations,
            contained_locations=contained_locations,
        )) 
Example #10
Source File: track.py    From performance_tracker with GNU General Public License v3.0 4 votes vote down vote up
def order_lines(feature_collection):
    features = copy.deepcopy(feature_collection['features'])
    ordered_coords = [features.pop()['geometry']['coordinates']]
    while len(features) > 0:
        min_dist = 1.e6
        idx = 0
        reverse = False
        insert_idx = 0
        for i, feature in enumerate(features):
            coord_list = feature['geometry']['coordinates']
            front_feat = coord_list[0][::-1]
            back_feat = coord_list[-1][::-1]
            front_coords = ordered_coords[0][0][::-1]
            back_coords = ordered_coords[-1][-1][::-1]
            d1 = distance(front_coords, front_feat)
            d2 = distance(front_coords, back_feat)
            d3 = distance(back_coords, front_feat)
            d4 = distance(back_coords, back_feat)
            
            if d1 < min_dist:
                min_dist = d1
                idx = i
                insert_idx = 0
                reverse = True
  
            if d2 < min_dist:
                min_dist = d2
                idx = i
                insert_idx = 0
                reverse = False
  
            if d3 < min_dist:
                min_dist = d3
                idx = i
                insert_idx = len(ordered_coords)
                reverse = False
  
            if d4 < min_dist:
                min_dist = d4
                idx = i
                insert_idx = len(ordered_coords)
                reverse = True
  
        feature = features.pop(idx)
        coords = feature['geometry']['coordinates']
        coords = coords[::-1] if reverse else coords
        ordered_coords.insert(insert_idx, coords)
    return [item for sublist in ordered_coords for item in sublist] 
Example #11
Source File: geoparse.py    From Geocoding-with-Map-Vector with GNU General Public License v3.0 4 votes vote down vote up
def geoparse(text):
    """
    This function allows one to geoparse text i.e. extract toponyms (place names) and disambiguate to coordinates.
    :param text: to be parsed
    :return: currently only prints results to the screen, feel free to modify to your task
    """
    doc = nlp(text)  # NER with Spacy NER
    for entity in doc.ents:
        if entity.label_ in [u"GPE", u"FACILITY", u"LOC", u"FAC", u"LOCATION"]:
            name = entity.text if not entity.text.startswith('the') else entity.text[4:].strip()
            start = entity.start_char if not entity.text.startswith('the') else entity.start_char + 4
            end = entity.end_char
            near_inp = pad_list(CONTEXT_LENGTH / 2, [x for x in doc[max(0, entity.start - CONTEXT_LENGTH / 2):entity.start]], True, padding) + \
                       pad_list(CONTEXT_LENGTH / 2, [x for x in doc[entity.end: entity.end + CONTEXT_LENGTH / 2]], False, padding)
            far_inp = pad_list(CONTEXT_LENGTH / 2, [x for x in doc[max(0, entity.start - CONTEXT_LENGTH):max(0, entity.start - CONTEXT_LENGTH / 2)]], True, padding) + \
                      pad_list(CONTEXT_LENGTH / 2, [x for x in doc[entity.end + CONTEXT_LENGTH / 2: entity.end + CONTEXT_LENGTH]], False, padding)
            map_vector = text2mapvec(doc=near_inp + far_inp, mapping=ENCODING_MAP_1x1, outliers=OUTLIERS_MAP_1x1, polygon_size=1, db=conn, exclude=name)

            context_words, entities_strings = [], []
            target_string = pad_list(TARGET_LENGTH, [x.text.lower() for x in entity], True, u'0')
            target_string = [word_to_index[x] if x in word_to_index else word_to_index[UNKNOWN] for x in target_string]
            for words in [near_inp, far_inp]:
                for word in words:
                    if word.text.lower() in word_to_index:
                        vec = word_to_index[word.text.lower()]
                    else:
                        vec = word_to_index[UNKNOWN]
                    if word.ent_type_ in [u"GPE", u"FACILITY", u"LOC", u"FAC", u"LOCATION"]:
                        entities_strings.append(vec)
                        context_words.append(word_to_index[u'0'])
                    elif word.is_alpha and not word.is_stop:
                        context_words.append(vec)
                        entities_strings.append(word_to_index[u'0'])
                    else:
                        context_words.append(word_to_index[u'0'])
                        entities_strings.append(word_to_index[u'0'])

            prediction = model.predict([np.array([context_words]), np.array([context_words]), np.array([entities_strings]),
                                        np.array([entities_strings]), np.array([map_vector]), np.array([target_string])])
            prediction = index_to_coord(REVERSE_MAP_2x2[np.argmax(prediction[0])], 2)
            candidates = get_coordinates(conn, name)

            if len(candidates) == 0:
                print(u"Don't have an entry for", name, u"in GeoNames")
                continue

            max_pop = candidates[0][2]
            best_candidate = []
            bias = 0.905  # Tweak the parameter depending on the domain you're working with.
            # Less than 0.9 suitable for ambiguous text, more than 0.9 suitable for less ambiguous locations, see paper
            for candidate in candidates:
                err = great_circle(prediction, (float(candidate[0]), float(candidate[1]))).km
                best_candidate.append((err - (err * max(1, candidate[2]) / max(1, max_pop)) * bias, (float(candidate[0]), float(candidate[1]))))
            best_candidate = sorted(best_candidate, key=lambda (a, b): a)[0]

            # England,, England,, 51.5,, -0.11,, 669,, 676 || - use evaluation script to test correctness
            print name, start, end
            print u"Coordinates:", best_candidate[1]


# Example usage of the geoparse function below reading from a directory and parsing all files.