Пример #1
0
 def greedy_path(self, points):
     gr = solve_tsp(self.matrix)
     init_path = gr.copy()
     for el in points:
         num = el.index
         init_path[gr.index(num)] = el
     return init_path
Пример #2
0
def make_traversal_plan(region_ids_yx, initial_id):
    id_to_neighbours_map = make_region_neighbours_map(region_ids_yx)
    max_id = 0
    for row in region_ids_yx:
        for _id in row:
            if _id > max_id:
                max_id = _id

    # TODO: try using this library instead:
    #       https://github.com/jvkersch/pyconcorde
    unreachable = 1000
    distance_half_matrix = []
    for a in range(1, max_id + 1):
        row = []
        for b in range(1, a):
            if b in id_to_neighbours_map[a]:
                row.append(1)
            else:
                row.append(unreachable)

        distance_half_matrix.append(row)
    last_row = [unreachable] * (max_id)

    distance_half_matrix.append(last_row)

    true_initial_id = initial_id - 1

    path = tsp.solve_tsp(distance_half_matrix,
                         optim_steps=10,
                         endpoints=(initial_id - 1, max_id))
    path.pop()

    return list(map(lambda x: x + 1, path))
    def tsp_solver(assigned_students):
        route = []
        for s in assigned_students:
            points = s['points']
            final = []
            results = []
            for p in points:
                results.append(
                    [p["latitude"], p["longitude"], p['student_id']])

            adjacency_matrix = optimizePickupSequence.generate_graph(results)
            sequence = solve_tsp(adjacency_matrix)
            tsp_dis = optimizePickupSequence.cal_totaldis(results, sequence)
            # When there is only one student, not need to find route
            if (len(sequence) == 1):
                final.append({
                    'student_id': results[0][2],
                    'latitude': results[0][0],
                    'longitude': results[0][1]
                })
            else:
                for k in sequence:
                    final.append({
                        'student_id': results[k][2],
                        'latitude': results[k][0],
                        'longitude': results[k][1]
                    })

            route.append({
                'mean': s['mean'],
                'school': s['school'],
                'location': s['location'],
                'pickup_sequence': final
            })
        return route
def handle_startboats(arg=0):
	
	global boat_speed
	global boat_capacity
	boat_speed = random.uniform(.2,1.0)
	boat_capacity = random.uniform(10,150)

	rospy.Rate(30)
	human_boat_check_sub()
        boat_location_sub()

	human_boat_check_pub()
	command = boat_auction__info_pub()
	ugvnav()
	time.sleep(2)
	resp = call_auctioning_service_client()
	metacluster_location_array = resp.metaclusters
	auction_info = resp.auction_assignments

	print "before if", auction_info, metacluster_location_array
	if ((metacluster_location_array != []) and (auction_info != [])):
		print "entered if"
		assigned_clusters_locations = get_relevant_clusters(auction_info,metacluster_location_array)
		print "got assigned clusters"
		cost_mat = setup_tsp(assigned_clusters_locations)
		print "got cost mat"
		path = solve_tsp( cost_mat )
		print "solved tsp"
		travel_using_tsp(path,assigned_clusters_locations)
		print "after travling"

	return True
Пример #5
0
def makePath(points):
    def to_key(p1, p2):
        p1, p2 = sorted([p1, p2])
        return (p1['local_idx'], p2['local_idx'])

    all_paths = make_all_paths(points)

    matrix = [[0] * len(points) for _ in range(len(points))]
    for (idx1, idx2), (path, size) in all_paths.items():
        matrix[idx1][idx2] = size
        matrix[idx2][idx1] = size

    indexes = solve_tsp(matrix)

    points_dict = {p['local_idx']: p for p in points}
    points_path = [points_dict[idx] for idx in indexes]
    print(indexes)

    full_path = []
    for p1, p2 in zip(points_path[:-1], points_path[1:]):
        path, _ = all_paths[to_key(p1, p2)]
        path = path[:]
        if path[0] != p1:
            path = list(reversed(path))
        full_path.extend(path)

    indexes = [p['index'] for p in points_path]
    return [(p['lat'], p['lon']) for p in full_path], indexes
Пример #6
0
def corrsort(features, use_tsp=False):
    """
    Given a features array, one feature per axis=0 entry, return axis=0 indices
    such that adjacent indices correspond to features that are correlated.

    cf. Traveling Salesman Problem. Not an optimal solution.

    use_tsp:
    Use tsp solver. See tsp_solver.greedy module that is used for this.
    Slows run-time considerably: O(N^4) computation, O(N^2) memory.

    Without use_tsp, both computation and memory are O(N^2).
    """

    correlations = np.ma.corrcoef(arrays.plane(features))
    if use_tsp: return tsp.solve_tsp(-correlations)

    size = features.shape[0]    
    correlations.mask[np.diag_indices(size)] = True
    
    # initialize results with the pair with the highest correlations.
    largest = np.argmax(correlations)
    results = [int(largest / size), largest % size]
    correlations.mask[:, results[0]] = True

    while len(results) < size:
        correlations.mask[:, results[-1]] = True
        results.append(np.argmax(correlations[results[-1]]))
            
    return results
Пример #7
0
def connect_dots_with_lines(dots):
    #
    lines = []
    #
    #
    # build upper triangular distance matrix between dots
    distance_matrix = [[0] * len(dots) for x in range(len(dots))]
    for i in range(len(dots)):
        for j in range(i + 1, len(dots)):
            d = distance_between(dots[i], dots[j])
            distance_matrix[i][j] = d
            distance_matrix[j][i] = d
    #
    #
    # ask for TSP solution
    path = solve_tsp(distance_matrix)
    #
    #
    # create lines
    last_node = dots[path[0]]
    for x in range(1, len(path)):
        next_node = dots[path[x]]
        lines.append((last_node, next_node))
        last_node = next_node
    #
    return lines
def label_images(n_splits=4):
    # Extract image features
    print('extract_features')
    if not os.path.exists(VGG16_FEATURES):
        files = _img_json_files()
        _extract_features(files)
    print('load feature')
    vgg16_features = np.load(VGG16_FEATURES)
    print('Loaded VGG16 features: ', vgg16_features.shape)

    print('sort images')
    # Sort images by similarity
    pdists = distance.pdist(vgg16_features)
    D = distance.squareform(pdists)
    path = solve_tsp(D)

    # Debug
    if False:
        import matplotlib.pyplot as plt
        files = _img_json_files()
        for p in path:
            img = cv2.imread(files[p])
            img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
            plt.imshow(img)
            plt.show()

    # Make n_splits labels
    labels = np.zeros(vgg16_features.shape[0]).astype(int)
    for idx, p in enumerate(path):
        labels[p] = idx % n_splits
    print(np.unique(labels))
    return labels
Пример #9
0
    def run(self, parameters):
        self.send_feedback('Waiting for task to start')
        yield self.wait_for_task_such_that(lambda task: task.state in ['ready', 'running'])
        path_msg = yield self.get_latching_msg(self.wayfinding_path_sub)
        poses = [ (yield self.geo_pose_to_enu_pose(geo_pose.pose)) for geo_pose in path_msg.poses]

        position = self.pose[0]

        #initialize distance matrix
        poses = poses + [position]
        array_size = len(poses)
        start_pose_index = array_size - 1
        dist_matrix = np.zeros( (array_size, array_size) )

        #fill up distance matrix
        for i in range(array_size):
            for j in range(array_size):
                dist_matrix[i][j] = np.linalg.norm(poses[i][0] - poses[j][0])

        #solve tsp algorithm (ensure start point is where boat is located) & remove current position from pose list
        path = solve_tsp(dist_matrix, endpoints=(start_pose_index,None))
        poses = poses[:start_pose_index]
        path = path[1:]

        #self.send_feedback('Sorted poses' + str(poses))
        yield self.wait_for_task_such_that(lambda task: task.state in ['running'])

        #do movements
        for index in path:
            self.send_feedback('Going to {}'.format(poses[index]))

            #Go to goal
            yield self.send_trajectory_without_path(poses[index])
Пример #10
0
    def optimal_solution(self):

        if self.n > 9:
            adj_matrix = nx.adjacency_matrix(self.graph)
            best_path = solve_tsp(adj_matrix.todense().tolist())

            if best_path[-1] == 0:
                best_path.pop()
            else:
                best_path = best_path[best_path.index(0) + 1:] + best_path[:best_path.index(0)]

            best_score = self.path_pay(best_path)
            return best_score, best_path

        optimal_path = None
        optimal_cost = float('inf')

        # brute force
        path = np.arange(self.n)[1:]
        for permutation in permutations(path):
            cost = self.path_pay(permutation)

            if cost < optimal_cost:
                optimal_cost = cost
                optimal_path = permutation

        return (optimal_cost, optimal_path)
Пример #11
0
def tsp_solver(clusters):
	cost_mat = setup_tsp(clusters)
	path = solve_tsp( cost_mat )
	path_array = [] 
	for index in path:
		path_array.append(clusters[index-1])
	#print(path_array)
	return path_array
Пример #12
0
 def opt_tours(self, dt):
     start = time.time()
     tour = path = solve_tsp(self.adjacency)
     cost = self.tour_length(tour)
     if cost < self.lowest_cost:
         print(cost)
         self.lowest_cost = cost
         self.shortest_tour = [self.targets[t] for t in tour]
Пример #13
0
    def generate_routes(self):
        # changing naN (that file input not have route) to a bigger number to not influence in better way
        mat = self.df.fillna(10000).values

        return solve_tsp(mat,
                         endpoints=(self.get_position_by_name(self.origin),
                                    self.get_position_by_name(
                                        self.destination)))
Пример #14
0
def traveling_salesman(colors, alg):

    # build a full matrix of cie2000 distances
    len_colors = len(colors)
    matrix = [[0 for i in range(len_colors)] for j in range(len_colors)]

    for x in range(len_colors):
        (x_red, x_green, x_blue) = colors[x]
        x_rgb = colors[x]
        x_lab = rgb2lab((x_red, x_green, x_blue))
        x_hsv = colorsys.rgb_to_hsv(x_red / 255.0, x_green / 255.0,
                                    x_blue / 255.0)
        x_hls = colorsys.rgb_to_hls(x_red / 255.0, x_green / 255.0,
                                    x_blue / 255.0)

        for y in range(len_colors):

            if x == y:
                matrix[x][y] = 0
                matrix[y][x] = 0
                continue

            if matrix[x][y] or matrix[y][x]:
                continue

            (y_red, y_green, y_blue) = colors[y]
            y_rgb = colors[y]

            if alg == "cie2000":
                y_lab = rgb2lab((y_red, y_green, y_blue))
                distance = delta_e_cie2000(x_lab, y_lab)

            elif alg == "HSV":
                y_hsv = colorsys.rgb_to_hsv(y_red / 255.0, y_green / 255.0,
                                            y_blue / 255.0)
                distance = get_hsv_distance(x_hsv, y_hsv)

            elif alg == "HLS":
                y_hls = colorsys.rgb_to_hls(y_red / 255.0, y_green / 255.0,
                                            y_blue / 255.0)
                distance = get_hls_distance(x_hls, y_hls)

            elif alg == "Lab":
                y_lab = rgb2lab((y_red, y_green, y_blue))
                distance = get_euclidean_lab_distance(x_lab, y_lab)

            elif alg == "RGB":
                distance = get_euclidean_distance_two_points(x_rgb, y_rgb)

            else:
                raise Exception("Implement {}".format(alg))

            matrix[x][y] = distance
            matrix[y][x] = distance

    #path = solve_tsp(matrix, endpoints=(0, -1))
    path = solve_tsp(matrix)
    return [colors[x] for x in path]
Пример #15
0
def tsp_solver(x):
    # reorder the trajectory according to the TSP solution
    shape = x.shape
    x = x.reshape(-1, 3)
    d = distance_matrix(x, x)
    t = solve_tsp(d)
    x = x[t, :]
    x = x.reshape(shape)
    return x
Пример #16
0
def kmeans_tsp(x):
    # reorder the trajectory according to the TSP solution
    shape = x.shape
    x = x.reshape(-1, 3)
    x = balanced_kmeans(shape[0], torch.from_numpy(x).float()).numpy()
    for i in range(shape[0]):
        d = distance_matrix(x[i, :, :], x[i, :, :])
        t = solve_tsp(d)
        x[i, :, :] = x[i, t, :]
    return x
Пример #17
0
 def compute_tsp(self):
     max_value = 30000
     if (self.data != None):
         if (len(self.features) > 0):
             if (len(self.features) <= 2):
                 order = range(0, len(self.features))
             else:
                 matData = 1 - cosine_similarity(np.transpose(self.data))
                 cities = solve_tsp(matData)
                 return {"cities": cities, "groupId": 0, "offset": 0}
Пример #18
0
    def giveDistanceIndiv(self, pop):
        N = len(pop)
        D = np.zeros((N, N), np.float32)
        for i, iIndiv in enumerate(pop):
            for j, jIndiv in enumerate(pop):
                D[i, j] = D[j, i] = np.count_nonzero(iIndiv - jIndiv)

        print(D)
        from tsp_solver.greedy import solve_tsp
        path = solve_tsp(D)
        for i in path[1::]:
            print(D[i, path[i - 1]] / float(len(iIndiv)))
Пример #19
0
def day9_1(data):
    #data = read_input(2015, "901")
    graph, cities = processInputAndBuildGraph(data)
    
    #print(cities)
    #for ds in graph:
    #    print(ds)
        
    path = solve_tsp(graph)
    print(path)
    result = path_cost(graph, path)
    AssertExpectedResult(207, result, 1)
    return result
Пример #20
0
    def nextGeneration(currentGen, eliteSize, mutationRate, greedy=False):
        popRanked = rankRoutes(currentGen)
        selectionResults = selection(popRanked, eliteSize)
        matingpool = matingPool(currentGen, selectionResults)
        children = breedPopulation(matingpool, eliteSize)
        nextGeneration = mutatePopulation(children, mutationRate)
        if not greedy:
            return nextGeneration

        path = solve_tsp(temp)
        nextGeneration.pop()
        nextGeneration.append(path)
        return nextGeneration
Пример #21
0
def main():
    '''Run tsp calc on address file.'''
    parser = argparse.ArgumentParser(description='TSP for addresses.')
    parser.add_argument('address_file', help='File with one address per line')
    parser.add_argument('api_key', help='Google Maps Distance Matrix API key')
    args = parser.parse_args()

    addresses = read_addresses(args.address_file)
    distances_dict = get_distances(addresses, args.api_key)
    distance_matrix = parse_distance_dict(distances_dict)
    path = solve_tsp(distance_matrix)

    print 'path:'
    for idx in path:
        print addresses[idx]
    print
    print 'cycle duration (sec):', calc_duration(path, distance_matrix)
Пример #22
0
def tsp_solver_master(sku_pick_seq, slots, graph, depot_node_id):
    from tsp_solver.greedy import solve_tsp
    from pickseq.py import sku_to_node_pick
    from graph.py import nx_dijkstra_dm
    global distance_matrix
    node_pick_seq = sku_to_node_pick(sku_pick_seq, slots)
    node_pick_seq = [depot_node_id] + node_pick_seq + [depot_node_id]
    distance_matrix = nx_dijkstra_dm(graph, node_pick_seq)
    route = solve_tsp(distance_matrix)
    result = []
    for stop in route:
        stop_node_id = node_pick_seq[stop]
        stop_slot_id = slot_pick_seq[stop]
        stop_sku_id = sku_pick_seq[stop]
        pick = {'SKU': stop_sku_id, 'Slot': stop_slot_id, 'Node': stop_node_id}
        result.append(pick)
    return result
Пример #23
0
def tsp_solver_master(sku_pick_seq,slots,graph,depot_node_id):
    from tsp_solver.greedy import solve_tsp
    from pickseq.py import sku_to_node_pick
    from graph.py import nx_dijkstra_dm
    global distance_matrix
    node_pick_seq = sku_to_node_pick(sku_pick_seq,slots)
    node_pick_seq = [depot_node_id] + node_pick_seq + [depot_node_id]
    distance_matrix = nx_dijkstra_dm(graph,node_pick_seq)
    route = solve_tsp(distance_matrix)
    result = []
    for stop in route:
        stop_node_id = node_pick_seq[stop]
        stop_slot_id = slot_pick_seq[stop]
        stop_sku_id = sku_pick_seq[stop]
        pick = {'SKU':stop_sku_id,'Slot':stop_slot_id,'Node':stop_node_id}
        result.append(pick)
    return result
Пример #24
0
def shortest_path(list_of_orders):
    master_ans = []
    print(list_of_orders)
    a = [(i.destination, i.priority) for i in list_of_orders]
    list_of_dest = [i[0] for i in a]
    list_of_dest = list(set(list_of_dest))


    print(list_of_dest)
    dis_mat = [[]]
    starting_pt = pick_shortest(Hospital.objects.get(id=1), list_of_dest)
    for i in range(1, len(list_of_dest)):
        dis_mat.append([dis_2_pt( list_of_dest[i] , list_of_dest[j]) for j in range(0, i)])
    print(dis_mat)
    master_ans += [list_of_dest[i] for i in solve_tsp(dis_mat)]

    return master_ans
Пример #25
0
def callback(data):
    # Read node distances from file
    # File location is in Home
    roomlist = [508, 507, 510]
    pub = rospy.Publisher('solvedPath', String, queue_size=10)
    csvPath = "~/Documents/catkin_ws/src/mailbot/"
    d = pd.read_csv("/".join([csvPath, "/config/weights.csv"]), header=None)
    d  = d.values

    rospy.loginfo("Received locations")

    # get nodes to traverse
    # node_list = np.asarray(data.data.split(), int)
    node_list = np.asarray(data.data.split(), int)
    nodes = rm.arrayToIndex(node_list)
    # nodes = np.empty((node_list.shape))
    #
    # for i in range(len(node_list)):
    #     try:
    #         nodes[i] = np.argwhere(roomlist == node_list[i])
    #     except IndexError:
    #         print('Room ', node_list[i], ' not valid.')
    #         nodes[i] = -1
    #print(nodes)
    # create a smaller distance matrix to solve from nodes to traverse
    row_idx = np.array(nodes)
    col_idx = np.array(nodes)
    dsub = d[row_idx[:, None], col_idx]

    # solve the tsp for the nodes desired
    relpath = solve_tsp(dsub)

    # stating a start and finish point solves our tour issue
    # relpath = solve_tsp(dsub, endpoints = (0,1)))

    # convert the solution path back to index of full matrix
    path = [0]*len(nodes)
    for j in range(0, len(relpath)):
        path[j] = nodes[relpath[j]]
    print("path: ", path)

    # print the path cost
    # print(path_cost(d, path))
    # print(path)
    pub.publish(str(path))
Пример #26
0
def make_path1(points):
    distances = []
    for i in range(0, len(points)):
        sub_distances = []
        for j in range(0, len(points)):
            distance = ((points[j].x - points[i].x)**2 +
                        (points[j].y - points[i].y)**2)**0.5
            sub_distances.append(distance)
        distances.append(sub_distances)

    last_index = len(points) - 1
    path_indexes = solve_tsp(distances, endpoints=(0, last_index))

    path = []
    for i in range(1, len(points)):
        index = path_indexes[i - 1]
        path.append(points[index])

    return path
def solve(person_list, table_types):
    # Create a distance matrix of persons
    num_people = len(person_list)
    a = zeros((num_people, num_people))
    a[:] = 1.0
    fill_diagonal(a, 0.0)

    # Set distance to friends very small (0.0)
    for person in person_list:
        if person.friend is None: continue
        a[person_list.index(person), person_list.index(person.friend)] = 0.0
        a[person_list.index(person.friend), person_list.index(person)] = 0.0

    # print a
    # print spatial.distance.squareform(a)

    # Solve the TSP for the distance matrix
    path = solve_tsp(a)
    # print path

    # Create the ordered seating list
    seating_list = []
    for segment in path:
        seating_list.append(person_list[segment])

    # Create a table list
    table_list = []

    for key, value in table_types.items():
        for i in range(0, value):
            table_list.append(Table(i, num_seats=key))

    # Assign people to tables
    person_iter = iter(seating_list)
    for table in table_list:
        while len(table.occupant_list) < table.seats:
            try:
                table.occupant_list.append(next(person_iter))
            except:
                break

    return table_list
def q9_2015_part1():
    input = get_input('9', '2015').splitlines()
    dist_matrix = []
    line_index = -1
    for row in range(8):  ##build the distance matrix
        dist_list = []
        for index in range(row):
            data = input[line_index].split()
            dist_list.append(int(data[4]))
            line_index -= 1
        dist_matrix.append(dist_list)
    ## solve the best path
    path = solve_tsp(dist_matrix)
    ## calculate total distance
    total_dist = 0
    for index in range(1, len(path)):
        total_dist += dist_matrix[max(path[index - 1], path[index])][min(
            path[index - 1], path[index])]

    return total_dist
Пример #29
0
def tsp(graph):
    matrix = []
    line = []

    for n in graph.nodes:
        for m in graph.nodes:
            if n == m:
                line.append(0)
            else:
                line.append(graph.distances[(n, m)])
        matrix.append(line)
        line = []

    path = solve_tsp(matrix)
    # print(path)
    # path.append(path[0])
    # print(path)
    # ToDo: count the distance in a proper way
    distance = 1000

    return distance, [str(p) for p in path]
Пример #30
0
 def new_board(self, start_node):
     """
     Returns a new game board for TSP
         - A game board is a tuple containing a distance matrix (ndarray) representation of a graph
         - A Path (list) for the current player
     """
     graph = np.zeros(shape=(self.nodes, self.nodes), dtype=np.float32)
     path = [start_node]
     for src in range(self.nodes):
         for dst in range(self.nodes):
             # nodes cannot connect to themselves
             if src != dst:
                 if graph[dst][src] != 0:
                     graph[src][dst] = graph[dst][src]
                 else:
                     graph[src][dst] = random.randint(0, 100)
     # get optimal solution
     self.solution = solve_tsp(graph)
     # print('sol', self.solution)
     self.optimal_path_length = self.get_path_length((graph, self.solution))
     return graph, path
Пример #31
0
def permutateFramesWithinScenes(distances_dict):
    '''
    Finds permutation of frames within a scene
    that minimizes the total optical flow distance
    Solver used is greedy traveling salesman
    or 2-opt heuristic
    '''
    solution = {}
    for scene in distances_dict:

        nbNodes = len(distances_dict[scene])

        if cfg.USE_DUMMY_NODE:
            scratch = range(nbNodes + 1)
            distance_matrix = np.zeros((nbNodes + 1, nbNodes + 1))
            distance_matrix[:nbNodes, :nbNodes] = distances_dict[scene]
        else:
            scratch = range(nbNodes)
            distance_matrix = distances_dict[scene]

        if cfg.TSP_SOLVER == 'greedy':
            solution[scene] = solve_tsp(distance_matrix)
        elif cfg.TSP_SOLVER == '2opt':
            solution[scene] = two_opt_refine(distance_matrix, scratch)

        if cfg.USE_DUMMY_NODE:
            solution[scene].remove(nbNodes)

    for scene in distances_dict:
        print "TSP distances for scene", scene, ":",\
            evaluate_distance(distances_dict[scene], solution[scene])

    # Further refine:
    if cfg.TSP_SOLVER == 'greedy' and cfg.REFINE_GREEDY_WITH_2OPT:
        solution[scene] = two_opt_refine(distance_matrix, solution[scene])
        for scene in distances_dict:
            print "TSP distances for scene", scene, ":",\
                evaluate_distance(distances_dict[scene], solution[scene])

    return solution
Пример #32
0
def main():
    path = []
    nation_name = [
        'Orvars', 'VG', 'GH', 'Hyttan', 'OG', 'Stocken', 'Wermlands', 'Glenns',
        'Snerikes', 'Bettys', 'Svantes', 'Kronan', 'VDala'
    ]

    def make_symetric_matrix(nation_name):
        """A function that makes a symetric matrix of the
           distances between the nations"""
        matrix = []
        for i in range(len(nation_name)):
            row = []
            for j in range(len(nation_name)):
                row.append(nations[nation_name[i]][nation_name[j]][0])
            matrix.append(row)
        return matrix

    def readable_information(path_i):
        """Turns the information into something readable"""
        path_distance = 0
        path_time = 0
        for i in path_i:
            path.append(nation_name[i])

        for i in range(len(path) - 1):
            path_distance += nations[path[i]][path[i + 1]][0]
            path_time += nations[path[i]][path[i + 1]][1]
            # path_time += 30

        print(path)
        print(path_distance, " meters")
        print(path_time, " minutes")

    matrix = make_symetric_matrix(nation_name)  # Get the matrix

    path_i = solve_tsp(matrix)  # Solves the ts-problem

    readable_information(path_i)  # Get the information
Пример #33
0
def main():
    path = []
    nation_name = ['Orvars', 'VG', 'GH', 'Hyttan', 'OG', 'Stocken',
                   'Wermlands', 'Glenns', 'Snerikes', 'Bettys',
                   'Svantes', 'Kronan', 'VDala']

    def make_symetric_matrix(nation_name):
        """A function that makes a symetric matrix of the
           distances between the nations"""
        matrix = []
        for i in range(len(nation_name)):
            row = []
            for j in range(len(nation_name)):
                row.append(nations[nation_name[i]][nation_name[j]][0])
            matrix.append(row)
        return matrix

    def readable_information(path_i):
        """Turns the information into something readable"""
        path_distance = 0
        path_time = 0
        for i in path_i:
            path.append(nation_name[i])

        for i in range(len(path) - 1):
                path_distance += nations[path[i]][path[i+1]][0]
                path_time += nations[path[i]][path[i+1]][1]
                # path_time += 30

        print(path)
        print(path_distance, " meters")
        print(path_time, " minutes")

    matrix = make_symetric_matrix(nation_name)  # Get the matrix

    path_i = solve_tsp(matrix)  # Solves the ts-problem

    readable_information(path_i)  # Get the information
Пример #34
0
def main():

    if len(sys.argv) > 1 and sys.argv[1] == "genres":
        genres = True
    else:
        genres = False

    ## get subset of db based on input.txt
    db, unfound_tracks = hlpr.processInput(genres = genres)

    cols = ['tempo', 'mode', 'acousticness', 'danceability', 'energy',
            'instrumentalness', 'liveness', 'speechiness', 'valence']
    if genres:
        cols = cols + GENRE_AGGREGATES

    X = hlpr.dataFrameToMatrix(db, cols_to_keep = cols)
    # X = X.fillna(0)
    X = dam.minMaxScaleData(X)
    # X2 = dam.transformPCA(X, 2)
    # clusters2 = dam.classifyUnsupervised(X2, 3)
    # clusters1 = dam.classifyUnsupervised(X, 3)

    method = raw_input(
        "Which method: Start and end? Enter 'both'.\nJust start song? Enter 'start'. >> "
    )

    if method == "both":
        D = sc.pdist(X.copy())
        D = sc.squareform(D)

        db_dict = db.to_dict('index')

        D_dict = dict(zip(db_dict, D))

        G = {}
        for k1 in db_dict:
            G[k1] = dict(zip(db_dict, D_dict[k1]))

        tspg.solve_tsp(D)

        def find_all_paths(graph, start, end, path=[]):
            path = path + [start]
            if start == end:
                return [path]
            if not graph.has_key(start):
                return []
            paths = []
            for node in graph[start]:
                if node not in path:
                    newpaths = find_all_paths(graph, node, end, path)
                    for newpath in newpaths:
                        paths.append(newpath)
            return paths

        start_artist = raw_input('Enter artist name of song to start with: ')
        start_title = raw_input('Enter title of song to start with: ')
        end_artist = raw_input('Enter artist name of song to end with: ')
        end_title = raw_input('Enter title of song to end with: ')

        df = db
        start = np.where((df.artist.str.lower() == start_artist.lower()) &
                         (df.title.str.lower() == start_title.lower()))[0][0]
        end = np.where((df.artist.str.lower() == end_artist.lower()) &
                       (df.title.str.lower() == end_title.lower()))[0][0]

        row = np.repeat(999, len(D))
        col = np.append(row, 0)
        col.shape = (len(col), 1)
        col[start] = 0
        col[end] = 0
        row[start] = 0
        row[end] = 0

        DD = np.append(D, [row], 0)
        DD = np.append(DD, col, 1)

        tsp = tspg.solve_tsp(DD)

        with open(os.path.join("../output", "walk.txt"), "w") as f:
            mid = np.where(np.array(tsp) == (len(DD) - 1))[0][0]
            if db.iloc[tsp[mid + 1], ].title.lower() == start_title:
                walk = np.concatenate([tsp[(mid + 1):len(tsp)], tsp[0:mid]])
            elif db.iloc[tsp[mid - 1], ].title.lower() == start_title:
                walk = np.concatenate([tsp[0:(mid)][::-1], tsp[(mid + 1):len(tsp)][::-1]])
            for w in walk:
                if w == tsp[0]:
                    print "----------------------------------------"
                print "{} - {}".format(db.iloc[w, ].artist,
                                           db.iloc[w, ].title)
            print("\n")
            for w in walk:
                print "spotify:track:{}".format(db.iloc[w, ].spotify_id)
                f.write("spotify:track:%s\n" % w)

    if method == "start":
        strategy = raw_input("Join songs by 'link' or by 'center'? ")
        artist = raw_input('Enter artist name: ')
        song = raw_input('Enter song name: ')

        ## center means songs are sorted/ordered by proximity to centroid song
        if strategy == "center":
            expanse = dam.expandToPoints(X.copy(), db, artist, song)
            ids = expanse.spotify_id.tolist()
            sptfy.writeIDsToURI(ids, "../output", "walk.txt")
            for i in ids:
                print "{} - {}".format(
                    db.artist.values[db.spotify_id.values == i][0],
                    db.title.values[db.spotify_id.values == i][0]
                )
            print("\n")
            for i in ids:
                print "spotify:track:{}".format(i)

        ## link means songs are strung together finding the next closest song to
        ## the previously added node
        elif strategy == "link":
            walk = dam.walkPoints(X.copy(), db, artist, song)
            hlpr.writeTextFile(walk, "../output", "walk.txt")
            for w in walk:
                print "{} - {}".format(
                    db.artist.values[
                        db.spotify_id.values == sptfy.stripSpotifyURI(w)
                    ][0],
                    db.title.values[
                        db.spotify_id.values == sptfy.stripSpotifyURI(w)
                    ][0]
                )
            print("\n")
            for w in walk:
                print w

        # cluster_groups1 = hlpr.separateMatrixClusters(X2, clusters1)
        # cluster_groups2 = hlpr.separateDataFrameClusters(db_subset, clusters2)
        # cluster_groups3 = hlpr.separateDataFrameClusters(db_subset, clusters1)
        # scatterplot(X, "fit_predict")

        ## open file in sublime text
        # call(["subl", "output/walk.txt"])

    if len(unfound_tracks) > 0:
        print "\nThese songs weren't found..."
        print "Please add them back to your playlist manually:"
        for item in unfound_tracks:
            print item.strip()
        print "\n"
Пример #35
0
#!/usr/bin/env python
import argparse
from numpy import loadtxt, genfromtxt, corrcoef, sum, log, arange
from numpy.random import rand
from scipy.spatial.distance import cdist
from pylab import pcolor, show, colorbar, xticks, yticks, savefig
from tsp_solver.greedy import solve_tsp

parser = argparse.ArgumentParser(
	description='Plot tsne output.')
parser.add_argument('-i', '--input', default='data')
args = parser.parse_args()

data = loadtxt('{0}/vectors'.format(args.input))

labels = []
with open('{}/words'.format(args.input)) as f:
	for line in f:
		labels.append(line.strip())

distanceMatrix = cdist(data, data, 'euclidean')
path = solve_tsp(distanceMatrix)
pcolor(data[path], cmap='binary')
savefig('{}/correlation.png'.format(args.input), figsize=(4,4), dpi=600)

for i in path:
	print(labels[i])
Пример #36
0
def answer_tsp(seq):
    '''Top level function for TSP'''
    graph = create_graph(seq)
    path = solve_tsp(graph)
    return path_to_weight(path, graph)
Пример #37
0
from tsp_solver.greedy import solve_tsp

#Prepare the square symmetric distance matrix for 3 nodes:
#  Distance from 0 to 1 is 1.0
#                1 to 2 is 3.0
#                0 to 2 is 2.0
D = [[ 0, 1.0, 2.0],
     [ 1.0, 0, 3.0],
     [ 2.0, 3.0, 0]]

path = solve_tsp( D )

# will print [1,0,2], path with total length of 3.0 units
print path
Пример #38
0
    l[n].append(b)

m = {}

for key, value in cnt.iteritems():
#    print key, value
    m[key] = [[0 for x in range(value)] for x in range(value)]

hits = {}

for key, value in cnt.iteritems():
    for i in range(0,value):
        for j in range(0,value):
            m[key][i][j] = math.hypot(l[key][i][0] - l[key][j][0], l[key][i][1] - l[key][j][1])
        
    path = solve_tsp( m[key] )
#    print path

    hits[key] = []

    for p in path:
#        print l[key][p]
        hits[key].append((t[key][0], l[key][p]))

print """
M48
FMAT,2
METRIC,TZ
"""

for i in t.keys():
Пример #39
0
station_2_index = {}
for index, station in enumerate(stations):
    station_2_index[station] = index


# Build our matrix.  
matrix = []
for _ in range(len(stations)):
    matrix.append([longest_possiable_trip] * len(stations))

for ((start, end), time) in times.items():
    start = station_2_index[start]
    end = station_2_index[end]
    matrix[start][end] = time

def pairs(i):
    i = iter(i)
    last_item = i.next()
    for item in i:
        yield last_item, item
        last_item = item

path = solve_tsp(matrix, optim_steps=10000)
path = [stations[index] for index in path]
print >>sys.stderr, "Total time:", sum(times.get(pair, longest_possiable_trip) for pair in pairs(path))
print " ".join(map(str, path))
    

    
Пример #40
0
        positions[tool_num].append(hit.position)

    hits = []

    # Optimize tool path for each tool
    for tool, count in iter(hit_counts.items()):

        # Calculate distance matrix
        distance_matrix = [[math.hypot(*tuple(map(sub, 
                                                  positions[tool][i], 
                                                  positions[tool][j]))) 
                            for j in iter(range(count))] 
                            for i in iter(range(count))]

        # Calculate new path
        path = solve_tsp(distance_matrix, 50)

        # Create new hits list
        hits += [DrillHit(f.tools[tool], positions[tool][p]) for p in path]

    # Update the file
    f.hits = hits
    f.filename = f.filename + '.optimized'
    f.write()
    
    # Print drill report
    print(f.report())
    print('Original path length:  %1.4f' % oldpath)
    print('Optimized path length: %1.4f' % sum(f.path_length().values()))

Пример #41
0
    cycleOffset1, cycleOffset2 = part1[1], part2[1]
    overLapSize = getOverlapSize(frac1, frac2,  cycleOffset1, cycleOffset2, lenOfCycle)
    overlap = (np.array(frac1[-overLapSize:]) + np.array(frac2[:overLapSize]))/2
    overlap = overlap.tolist()
    newFrac = pe.toList(frac1[:-overLapSize]) + overlap + pe.toList(frac2[overLapSize:])
    return (newFrac, cycleOffset1)

mat = []
for p1 in minedParts:
    row=[]
    for p2 in minedParts:
        dis = getDistanceBetweenFracs(p1, p2, lenOfCycle)
        row.append(dis)
    mat.append(row)
print mat
path = solve_tsp( mat )
print path
#whole = qu.orderWithCost(minedParts, getDistanceBetweenFracs, appendFracs)
whole = minedParts[path[0]]
for i in path[1:]:
    whole = appendFracs(whole, minedParts[path[i]], lenOfCycle)
whole = whole[0]
    
plt.figure()
whole = ma.movingAverage(whole, 10, 1.3)
plt.plot(whole)
#plt.plot()
#plt.show()
periods =[]
strides = []
stances = []
Пример #42
0
    lookup[track] = x
    track += 1

elements = [[100000 for y in range(track)] for x in range(track)]
# print elements

for x in range(track):
    elements[x][x] = 0

for path in paths:
    coord_1 = rename[path.node_1]
    coord_2 = rename[path.node_2]
    elements[coord_1][coord_2] = -int(path.distance)
    elements[coord_2][coord_1] = -int(path.distance)

solution = solve_tsp(elements)
# print solution

print lookup
readable = []
for x in solution:
    # print lookup[x]
    readable.append(lookup[x])
    # pass
print readable

tot_dist = 0
for i in range(len(readable)-1):
    pass_one = []
    pass_one += (get_all_containing(readable[i], paths))
    pass_two = []