Beispiel #1
0
    def test_distance_works_with_1d_arrays(self):
        """The code is vectorized for 2d arrays, but should work for 1d as well
        """
        source = sources[0]
        destination = destinations[0]

        distances.great_circle_distance_matrix(source, destination)
Beispiel #2
0
    def test_matrix_has_proper_shape(self):
        """N sources and M destinations should produce an (N x M) array"""
        distance_matrix = distances.great_circle_distance_matrix(
            sources, destinations)

        N, M = sources.shape[0], destinations.shape[0]
        assert distance_matrix.shape == (N, M)
Beispiel #3
0
async def get_route(places_ids: List[int], lat: float, lon: float):
    places = await data.get_places_by_ids(places_ids)

    if len(places) <= 1:
        return []

    sources = np.array([[lat, lon]])
    i = 0
    for place in places:
        print('index', i)
        i += 1
        print('id', place['id'])
        place_coords = np.array([[place['lat'], place['lon']]])
        sources = np.concatenate((sources, place_coords))

    distance_matrix = great_circle_distance_matrix(sources)
    permutation, distance = solve_tsp_dynamic_programming(distance_matrix)

    print(permutation)

    route = []
    for place_index in permutation[1:]:
        print('index', place_index - 1)
        print('id', places[place_index - 1]['id'])
        route.append(places[place_index - 1])

    return [Place(**place) for place in places]
def tsp(data):
    import numpy as np
    from python_tsp.distances import great_circle_distance_matrix

    sources = np.array(data)
    distance_matrix = great_circle_distance_matrix(sources)
    from python_tsp.distances import tsplib_distance_matrix
    from python_tsp.heuristics import solve_tsp_local_search, solve_tsp_simulated_annealing

    permutation, distance = solve_tsp_simulated_annealing(distance_matrix)
    return permutation, distance
Beispiel #5
0
    def test_square_matrix_is_symmetric(self):
        distance_matrix = distances.great_circle_distance_matrix(
            sources, sources)

        assert np.allclose(distance_matrix, distance_matrix.T)
Beispiel #6
0
    def test_square_matrix_has_zero_diagonal(self):
        """Main diagonal is the distance from a point to itself"""
        distance_matrix = distances.great_circle_distance_matrix(sources)

        assert np.all(np.diag(distance_matrix) == 0)
Beispiel #7
0
    def test_all_elements_are_non_negative(self):
        """Being distances, all elements must be non-negative"""
        distance_matrix = distances.great_circle_distance_matrix(
            sources, destinations)

        assert np.all(distance_matrix >= 0)
Beispiel #8
0
def text_order_in_frame(text_boxes: List[Dict[str, Any]]) -> List[str]:
    if len(text_boxes) == 0:
        return []
    id_to_text = {}
    for text in text_boxes:
        id = text["@id"]
        id_to_text[id] = text["#text"]
    frames_dict = {}
    x_max = -1
    x_min = 2000
    y_max = -1
    y_min = 2000
    # Find the min
    for frame in text_boxes:
        if int(frame["@xmin"]) < x_min:
            x_min = int(frame["@xmin"])
        if int(frame["@ymin"]) < y_min:
            y_min = int(frame["@ymin"])
        if int(frame["@xmax"]) > x_max:
            x_max = int(frame["@xmax"])
        if int(frame["@ymax"]) > y_max:
            y_max = int(frame["@ymax"])

    for frame in text_boxes:
        id = frame["@id"]
        topright = (int(frame["@xmax"]), int(frame["@ymin"]))
        botleft = (int(frame["@xmin"]), int(frame["@ymax"]))
        n_tr = (round((topright[0] - x_min)), round((topright[1] - y_min)))
        n_bl = (round((botleft[0] - x_min)), round((botleft[1] - y_min)))
        next_center = ((n_tr[0] + n_bl[0]) / 2, (n_tr[1] + n_bl[0]) / 2)
        frames_dict[id] = (n_tr, n_bl, next_center)

    toprightmost = list(frames_dict.keys())[0]
    toprightmostvalue = (
        (y_max - y_min) -
        frames_dict[toprightmost][0][1]) + frames_dict[toprightmost][0][0]
    for id, (tr, bl, c) in frames_dict.items():
        value = ((y_max - y_min) - tr[1]) + tr[0]
        if value == toprightmostvalue and tr[1] < frames_dict[toprightmost][0][
                1]:
            toprightmost = id
        elif value > toprightmostvalue:
            toprightmost = id
            toprightmostvalue = value

    idx_to_id = {0: toprightmost}
    i = 1
    for id, (tr, bl, c) in frames_dict.items():
        if id == toprightmost:
            continue
        idx_to_id[i] = id
        i += 1

    sources = []
    for i in range(len(idx_to_id)):
        sources.append(frames_dict[idx_to_id[i]][2])

    distance_matrix = great_circle_distance_matrix(np.array(sources))
    distance_matrix[:, 0] = 0
    if len(sources) > 20:
        text_box_order, _ = solve_tsp_simulated_annealing(distance_matrix)
    else:
        text_box_order, _ = solve_tsp_dynamic_programming(distance_matrix)

    final_order = []
    for idx in text_box_order:
        final_order.append(id_to_text[idx_to_id[idx]])
    return final_order
    for inst2 in Institutos:
        if inst1 != inst2:
            gmap.plot([inst1[1], inst2[1]], [inst1[2], inst2[2]],
                      'green',
                      edge_width=1)

# Draw the map to an HTML file:
gmap.draw('map.html')

# Solve TSP
matrix = [[-22.81713425394216, -47.06973932371405]]
for inst in Institutos:
    matrix.append([inst[1], inst[2]])

min = 100000000

distance_matrix = great_circle_distance_matrix(matrix)

# for i in range(1, 50):
permutation, distance = solve_tsp_simulated_annealing(distance_matrix)
# if distance < min:
#     min = distance
#     min_dist = distance
#     min_perm = permutation

print(distance)
print(permutation)
print(len(permutation))
for i in range(1, len(permutation)):
    print(Institutos[permutation[i] - 1][0])