예제 #1
0
def calculate_route(super_matrix, shopping_list):
    shopping_list.append("0")  # go through enterance
    bfs, routes = calc_distance_between_all_list(super_matrix, shopping_list)
    bfs = sorted(bfs)
    (new_input, input_converter_dict) = input_converter(bfs)

    # Initialize fitness function object using dist_list
    fitness_dists = mlrose.TravellingSales(distances=new_input)
    # Define optimization problem object
    problem_fit = mlrose.TSPOpt(length=len(shopping_list),
                                fitness_fn=fitness_dists,
                                maximize=False)
    # Solve problem using the genetic algorithm
    # best_state, best_fitness = mlrose.genetic_alg(problem_fit, random_state = 2)
    best_state, best_fitness = mlrose.genetic_alg(problem_fit,
                                                  mutation_prob=0.2,
                                                  max_attempts=200,
                                                  pop_size=200,
                                                  random_state=0)

    output_converter_dict = dict(
        (v, k) for k, v in input_converter_dict.items())
    final_result = [output_converter_dict[x] for x in best_state]
    register_index = final_result.index("0")
    final_result = final_result[register_index:] + final_result[:register_index]
    final_route = []

    for (k, v) in zip(final_result, final_result[1:] + final_result[:1]):
        for (x, y, z) in routes:
            if k == x and v == y:
                final_route += z
            elif k == y and v == x:
                final_route += z[::-1]

    return final_route, items_coor(super_matrix, shopping_list)
예제 #2
0
def gera_grafo(df) -> Grafo:
    global grafo

    grafo = Grafo(df)

    for i in range(len(colunas)):
        # Pega o nome da cidade pelo índice
        cidade_origem = colunas[i]
        for j in range(len(colunas)):
            # Pega o peso e o destino da aresta e adiciona no objeto Grafo
            destino = df.index[j]
            peso = df.iloc[j][cidade_origem]
            #aresta = dict(rota=(cidade_origem, destino), peso=peso)
            if peso != '-':
                aresta = (int(cidade_origem), int(destino), int(peso))
                grafo.adiciona_arestas(aresta)

    fitness = mlrose.TravellingSales(distances=grafo.arestas)
    # Define optimization problem object
    problem_fit = mlrose.TSPOpt(length=8, fitness_fn=fitness, maximize=False)
    best_state, best_fitness = mlrose.genetic_alg(problem_fit,
                                                  mutation_prob=0.2,
                                                  max_attempts=100,
                                                  random_state=2)
    print(fitness)
    return grafo
예제 #3
0
def find_route(n, matrix, time_limit):
    good = []
    for i in range(1, 2**(n - 1)):
        bin = binary(i, n - 1) + "1"
        iArr = []
        posArr = []
        for j in range(n - 1):
            if (bin[j] == '1'):
                iArr.append(j)
                posArr.append(locations[j])

        if (len(iArr) > 1):
            new_mat = getMat(iArr, matrix)
            dist_list = []
            for j in range(len(iArr)):
                for k in range(j + 1, len(iArr)):
                    dist_list.append((j, k, new_mat[j][k]))

            fitness_dists = mlrose.TravellingSales(distances=dist_list)
            problem_fit = mlrose.TSPOpt(length=len(iArr),
                                        fitness_fn=fitness_dists,
                                        maximize=False)
            best_state, best_fitness = mlrose.genetic_alg(problem_fit,
                                                          random_state=2)

            best_state_fr = []
            for k in range(len(iArr)):
                best_state_fr.append(iArr[best_state[k]])

            if (best_fitness < time_limit):
                good.append(best_state_fr)

    return good
예제 #4
0
def encuentra_circuito(ls_basicas):

    n_bas = [i for i in range(len(ls_basicas))]
    comb = itertools.combinations(n_bas, 2)

    dist_list = []
    for i in comb:
        costo = aptitud2(ls_basicas[i[0]], ls_basicas[i[1]])
        dist_list.append((i[0], i[1], costo))
        #print(ls_basicas[i[0]], ls_basicas[i[1]], costo)

    # Initialize fitness function object using dist_list
    fitness_dists = mlrose.TravellingSales(distances=dist_list)
    problem_fit = mlrose.TSPOpt(length=len(ls_basicas),
                                fitness_fn=fitness_dists,
                                maximize=True)
    best_state, best_fitness = mlrose.genetic_alg(problem_fit, random_state=2)
    #print(best_state)
    #print(best_fitness)

    # =============================================================================
    #     for i in best_state:
    #         print(ls_basicas[i])
    # =============================================================================
    return list(best_state), best_fitness / 2
예제 #5
0
def main():
    name_of_exp = "One Max"
    # Create list of city coordinates
    coords_list = [(1, 1), (4, 2), (5, 2), (6, 4), (4, 4), (3, 6), (1, 5), (2, 3)]
    mimic = []
    # Initialize fitness function object using coords_list
    fitness_coords = mlrose.TravellingSales(coords=coords_list)
    problem = mlrose.TSPOpt(length=8, fitness_fn=fitness_coords,
                            maximize=False)
    z_s = ['RHC', 'SA', 'GA', 'MIMIC']
    for i in [0.1,0.2,0.3,0.4,0.5]:
        best_state, best_fitness, learning_curve, timing_curve = mlrose.genetic_alg(problem, pop_size=100,
                                                                              mutation_prob=i,
                                                                              max_attempts=100,
                                                                              max_iters=100, curve=True,
                                                                              random_state=1)
        mimic.append(learning_curve)
        print(i)
        print(best_fitness)
    for x, z in zip([0.1,0.2,0.3,0.4,0.5], mimic):
        plt.plot(z, label=str(x))
    plt.legend()
    plt.title('GA Randomized Optimization MutationProb vs Fitness Curve (TSP)')
    plt.xlabel('Function iteration count')
    plt.ylabel('Fitness function value')
    plt.show()
예제 #6
0
def rank(fnames, save=True):

    dist_mat = np.load(fnames['dmat'])
    dist_list = mat2tuples(dist_mat)

    # define fitness function object
    fitness_dists = mlrose.TravellingSales(distances=dist_list)

    # define optimization problem object
    n = dist_mat.shape[0]
    problem_fit = mlrose.TSPOpt(length=n,
                                fitness_fn=fitness_dists,
                                maximize=False)

    # solve problem using the genetic algorithm
    best_state, best_fitness = mlrose.genetic_alg(problem_fit,
                                                  mutation_prob=0.2,
                                                  max_attempts=100,
                                                  random_state=2)

    # retrieve ranked list
    cand = load(fnames['cand'])
    ranked_cand = cand.loc[best_state]

    # save the output
    fname_ranked = None
    if save:
        fname, ext = os.path.splitext(fnames['cand'])
        fname_ranked = fname + '_ranked' + ext
        write(fname_ranked, ranked_cand)
        print('Ordered candidates saved to {}'.format(fname_ranked))

    return fname_ranked
예제 #7
0
def tsp(dd,l):
    state=[]
    for i in range(0,len(dd)):
      fitness_dists = mlrose.TravellingSales(distances = dd[i])
      problem_fit = mlrose.TSPOpt(length = len(l[i]), fitness_fn = fitness_dists, maximize=False)
      best_state, best_fitness = mlrose.genetic_alg(problem_fit, random_state = 2)
      state.append(best_state.tolist())
    return(state)
예제 #8
0
def api_tsp():
    # Check if an ID was provided as part of the URL.
    # If ID is provided, assign it to a variable.
    # If no ID is provided, display an error in the browser.
    places_to_visit = []
    if 'places' in request.args:
        temp = request.args['places']
        splitItems = temp.split(",")
        # listTemp = [int(i) for i in splitItems]
        print(request.args['places'])
        places_to_visit = splitItems
        # id = int(request.args['id'])
    else:
        return "Error: No id field provided. Please specify an id."

    # Create an empty list for our results
    results = []

    distance_matrix=[]
    for i in range(len(places_to_visit)):
        for j in range(i+1,len(places_to_visit)):
            origin=places_to_visit[i]
            dest=places_to_visit[j]
            key=(origin,dest)

            req='https://maps.googleapis.com/maps/api/distancematrix/json?origins=place_id:'+origin+'&destinations=place_id:'+dest+'&key='+my_API_key
            Response = requests.get(req)
            Response=Response.json()

            #pprint.pprint(Response["rows"][0]["elements"][0]["duration"]["value"])
            value=Response["rows"][0]["elements"][0]["duration"]["value"] #We get the time duration is seconds
            new_element=(i,j,value)
            distance_matrix.append(new_element)
    fitness = mlrose.TravellingSales(distances = distance_matrix)
    # We want to visit all the places of our list "places_to_visit"
    problem = mlrose.TSPOpt(length = len(places_to_visit), fitness_fn = fitness,
                                maximize=False)

    best_state, best_fitness = mlrose.genetic_alg(problem, random_state = 0)
    ordered_places_to_visit=[]
    for i in best_state:
      ordered_places_to_visit.append(places_to_visit[i])
    print(places_to_visit)

    temp = {}
    temp['results'] = ordered_places_to_visit
    results.append(temp)
    # Loop through the data and match results that fit the requested ID.
    # IDs are unique, but other fields might return many results
    # for book in books:
    #     if book['id'] in listTemp:
    #         results.append(book)

    # Use the jsonify function from Flask to convert our list of
    # Python dictionaries to the JSON format.
    return jsonify(results)
예제 #9
0
def find_best_path(points_data, random_state=0, use_coords=True):
    '''Find the shortest closed path (in euclidean distance)
    using Elastic Net Algorithm in mlrose package.'''
    # tuning curve size: (numNeruo, numBin) (might be high dimensional: numNeuro>3)
    # numBin = num_pts
    points_data = np.array(points_data)
    if len(points_data.shape) == 1:
        points_data = points_data.reshape((1, points_data.size))
    num_pts = points_data.shape[1]  # number of points

    def euclidean_distance(x, y):
        return np.sqrt(np.sum((x - y)**2))

    if use_coords:
        coords_list = []
        for i in range(num_pts):
            coords_list += [tuple(points_data[:, i])]
        # Initialize fitness function object using coords_list
        fitness = mlrose.TravellingSales(coords=coords_list)
    else:
        # use euclidean distances computed

        dist_list = []
        for i in range(num_pts):
            for j in range(num_pts):
                if i != j:
                    dist_list.append(
                        (i, j,
                         euclidean_distance(points_data[:, i],
                                            points_data[:, j])))
        # Initialize fitness function object using dist_list
        fitness = mlrose.TravellingSales(distances=dist_list)

    problem_fit = mlrose.TSPOpt(length=num_pts,
                                fitness_fn=fitness,
                                maximize=False)

    # Solve problem using the genetic algorithm
    best_path, best_path_len = mlrose.genetic_alg(problem_fit,
                                                  random_state=random_state)

    return best_path, best_path_len  # length of closed curve
예제 #10
0
    def get_genetic_path(self):
        """
        Return an approximate solution length to the TSP problem
        """

        fitness_coords = mlrose.TravellingSales(coords=self.coords)

        dist_list = list(self.G.edges.data('weight'))
        fitness_dists = mlrose.TravellingSales(distances=dist_list)

        problem_fit = mlrose.TSPOpt(length=self.nodes,
                                    fitness_fn=fitness_coords,
                                    maximize=False)

        best_state, best_fitness = mlrose.genetic_alg(problem_fit,
                                                      random_state=2,
                                                      mutation_prob=0.2,
                                                      max_attempts=100)

        return best_fitness
def calc_shortest_route_mlrose(
        systems: Iterable[Dict]) -> Tuple[List[Dict], float]:
    # See https://mlrose.readthedocs.io/en/stable/source/tutorial2.html#
    fitness_distances = mlrose.TravellingSales(
        distances=calc_distances(systems))
    problem_fit = mlrose.TSPOpt(length=len(systems),
                                fitness_fn=fitness_distances,
                                maximize=False)
    best_state, best_fitness = mlrose.genetic_alg(problem_fit,
                                                  random_state=20,
                                                  max_attempts=20)
    return ([systems[index] for index in best_state], best_fitness)
예제 #12
0
    def _cal_route(self):
        """ based on TSP solver """

        dist_list = self._build_dist_list()
        fitness_dists = mlrose.TravellingSales(distances=dist_list)
        problem_fit = mlrose.TSPOpt(length=len(self._places),
                                    fitness_fn=fitness_dists,
                                    maximize=False)
        best_state, best_fitness = mlrose.genetic_alg(problem_fit,
                                                      random_state=2)

        return best_state
예제 #13
0
def metaheuristic(dist, meta=None, nnodes=None, **kwargs):
    # fit data
    fit_dist = mr.TravellingSales(distances=dist)

    # define TSP
    fit_problem = mr.TSPOpt(length=nnodes, fitness_fn=fit_dist, maximize=False)

    # define optmization metaheuristic
    # kwargs are parameters to the metaheuristic
    best_state, best_fit = meta(fit_problem, **kwargs)

    return (best_state, best_fit)
예제 #14
0
 def _do_tsp(self, dist_list):
     """Do the actual travelling salesperson."""
     dist_list.sort(key=lambda x: x[0])
     length = int(self._get_max_index_value_in_dists(dist_list) + 1)
     try:
         fitness_dists = mlrose.TravellingSales(distances=dist_list)
         problem_fit = mlrose.TSPOpt(
             length=length, fitness_fn=fitness_dists, maximize=False)
         best_state, best_fitness = mlrose.genetic_alg(
             problem_fit, mutation_prob=0.2, max_attempts=50)
     except Exception:
         print(f"tsp failed. dist_list: {dist_list}")
         raise
     return best_state
예제 #15
0
파일: app.py 프로젝트: gecid-aia/unroute-me
def shortest_path(coords, start, end):
    tsp_fitness = mlrose.TravellingSales(coords=coords)

    def filter_endpoints(state):
        if state[0] == start and state[-1] == end:
            return tsp_fitness.evaluate(state)
        else:
            return math.inf

    fitness = mlrose.CustomFitness(filter_endpoints, 'tsp')
    problem = mlrose.TSPOpt(length=len(coords),
                            fitness_fn=fitness,
                            maximize=False)
    path, length = mlrose.genetic_alg(problem, random_state=2)
    return [coords[i] for i in path]
예제 #16
0
def findSolution():
    fitness_coords = mlrose.TravellingSales(coords=coords_list)
    problem_fit = mlrose.TSPOpt(length=48,
                                fitness_fn=fitness_coords,
                                maximize=False)
    best_state, best_fitness = mlrose.genetic_alg(problem_fit,
                                                  mutation_prob=0.2,
                                                  max_attempts=100,
                                                  random_state=2)
    json_response = json.dumps({
        "bestState": best_state.tolist(),
        "bestFitness": best_fitness.tolist()
    })
    print(json_response)
    return json_response
    def __init__(self, my_map):

        self.my_map = my_map
        self.my_map_np = np.asarray(self.my_map)

        # analysis the map
        self.bound_cells = mark_boundaries(self.my_map_np)
        print('Find Minimal Set Cover')

        start = datetime.datetime.now()

        self.key_points, self.key_pt_dirs, self.key_pt_cover_bd_idx = find_min_set_cover(
            self.bound_cells)
        self.state_dist, self.state_space = gen_solution_space(
            self.bound_cells, self.key_points, self.key_pt_dirs, 0.1, 50)

        print("Time for Minimal Set Cover is ",
              datetime.datetime.now() - start)

        # run the TSP to initialize
        print('Run TSP on finding vertices cover')

        start = datetime.datetime.now()

        fitness_function = mlrose.TravellingSales(distances=self.state_dist)
        problem_fit = mlrose.TSPOpt(length=len(self.state_space),
                                    fitness_fn=fitness_function,
                                    maximize=False)

        # Solve the problem using the genetic algorithm
        best_state, best_fitness = mlrose.genetic_alg(problem_fit,
                                                      random_state=5)
        self.best_state = best_state

        # extract states
        idx_2_state_spaces = {}
        for key, value in self.state_space.items():
            idx_2_state_spaces[value] = key
        state_dict = [
            idx_2_state_spaces[i].split("-") for i in self.best_state
        ]
        self.state_dict = [(self.key_points[int(s[0])], s[1])
                           for s in state_dict]

        if np.isinf(best_fitness):
            print('Error when finding TSP')

        print("Time for TSP is ", datetime.datetime.now() - start)
예제 #18
0
파일: demo.py 프로젝트: dfd/CS7641_hw02
def tsp_problem():
    coords_list = [(1, 1), (4, 2), (5, 2), (6, 4), (4, 4), (3, 6), (1, 5),
                   (2, 3)]
    fitness_coords = mlrose.TravellingSales(coords=coords_list)

    # Define optimization problem object
    problem_fit = mlrose.TSPOpt(length=8,
                                fitness_fn=fitness_coords,
                                maximize=True)

    best_state, best_fitness = mlrose.genetic_alg(problem_fit, random_state=2)

    print(best_state)
    print(best_fitness)

    best_state, best_fitness = mlrose.genetic_alg(problem_fit,
                                                  mutation_prob=0.2,
                                                  max_attempts=100,
                                                  random_state=2)
예제 #19
0
    def _map_routing(self) -> list:
        """Returns the best path to traverse points given by geo-coordinates.
        """
        # Lat and Lon of each order
        geo_points = self._get_map_coordinates()
        # Sales travelling instance
        fitness_coordinates = mlrose.TravellingSales(coords=geo_points)
        # Fit problem
        problem_fit = mlrose.TSPOpt(length=len(self.orders),
                                    fitness_fn=fitness_coordinates,
                                    maximize=False)
        # Best state result
        best_state, _ = mlrose.genetic_alg(problem_fit,
                                           pop_size=200,
                                           mutation_prob=0.2,
                                           max_attempts=100,
                                           max_iters=10,
                                           random_state=2)

        return best_state
예제 #20
0
    def _price_routing(self) -> list:
        """Returns the best path to traverse geopoints based on
        the cost between each of these pairs.
        """
        triplets = self._get_price_triplets()
        # Sales travelling instance
        fitness_prices = mlrose.TravellingSales(distances=triplets)
        # Fit problem
        problem_fit = mlrose.TSPOpt(length=len(self.orders),
                                    fitness_fn=fitness_prices,
                                    maximize=False)

        best_state, _ = mlrose.genetic_alg(problem_fit,
                                           pop_size=200,
                                           mutation_prob=0.2,
                                           max_attempts=100,
                                           max_iters=10,
                                           random_state=2)

        return best_state
예제 #21
0
def tsp_zone_distance(transformed_df, main_df):
    zones = ["D1", "D2", "D3", "D4", "D5", "D6"]
    unpivoted_df = pd.melt(transformed_df,
                           id_vars=['Id_Cliente'],
                           var_name="zones")
    unpivoted_df = unpivoted_df[unpivoted_df.value > 0]
    joined_df = unpivoted_df.merge(main_df[["Id_Cliente", "lat", "lon"]],
                                   on="Id_Cliente",
                                   how="left")
    total_distance = []
    for zone in zones:
        fitness_coords = mlrose.TravellingSales(coords=joined_df[
            joined_df["zones"] == zone][["lat", "lon"]].to_numpy())
        problem_fit = mlrose.TSPOpt(
            length=joined_df[joined_df["zones"] == zone].shape[0],
            fitness_fn=fitness_coords,
            maximize=False)
        best_state, best_fitness = mlrose.genetic_alg(problem_fit,
                                                      random_state=12)
        total_distance.append(best_fitness)
    print(total_distance)
    return (sum(total_distance))
예제 #22
0
    def solve_method(self, graph, current_node):
        nodes = list(graph.nodes) + [self.start]
        nodes.sort(key=lambda x: x.index)

        dist_list = [(node1.index, node2.index, node1.compute_distance(node2))
                     for node1 in nodes for node2 in nodes
                     if node1.index < node2.index]

        fitness_coords = mlrose.TravellingSales(
            coords=[node.get() for node in nodes], distances=dist_list)

        problem_fit = mlrose.TSPOpt(length=len(nodes),
                                    fitness_fn=fitness_coords,
                                    maximize=False)
        self.path, self.cost = mlrose.genetic_alg(problem_fit,
                                                  mutation_prob=0.2,
                                                  max_attempts=100,
                                                  random_state=2)

        self.path = [graph.get(node) for node in self.path]
        display_path(self.ax, self.path)

        return time.process_time() - self.time
예제 #23
0
def distance_optim(x_coordinates, y_coordinates):
    # Create the distance list for cell pairs
    # Unfortunately, cell indices starts from zero for mlrose
    #dist_list = [(0, 1, distance(x_coordinates,y_coordinates,0,1)), (0, 2, distance(x_coordinates,y_coordinates,0,2)),\
    #             (1, 3, distance(x_coordinates,y_coordinates,1,3)), (2, 3, distance(x_coordinates,y_coordinates,2,3)),\
    #             (3, 4, distance(x_coordinates,y_coordinates,3,4)), (3, 5, distance(x_coordinates,y_coordinates,3,5)),\
    #             (4, 6, distance(x_coordinates,y_coordinates,4,6)), (5, 6, distance(x_coordinates,y_coordinates,5,6)),\
    #             (6, 7, distance(x_coordinates,y_coordinates,6,7)), (6, 8, distance(x_coordinates,y_coordinates,6,8)),\
    #             (7, 9, distance(x_coordinates,y_coordinates,7,9)), (8, 9, distance(x_coordinates,y_coordinates,8,9)),\
    #             (9, 10, distance(x_coordinates,y_coordinates,9,10)), (9, 11, distance(x_coordinates,y_coordinates,9,11)),\
    #             (10, 12, distance(x_coordinates,y_coordinates,10,12)), (11, 12, distance(x_coordinates,y_coordinates,11,12))]

    dist_list3 = [(0, 1, distance(x_coordinates,y_coordinates,0,1)), (0, 2, distance(x_coordinates,y_coordinates,0,2)),\
                 (1, 3, distance(x_coordinates,y_coordinates,1,3)), (2, 3, distance(x_coordinates,y_coordinates,2,3)),\
                 (3, 4, distance(x_coordinates,y_coordinates,3,4)), (3, 5, distance(x_coordinates,y_coordinates,3,5))]

    # Define a fitness function object
    fitness_dists = mlrose.TravellingSales(distances=dist_list3)
    # Define a optimization problem object
    problem_fit = mlrose.TSPOpt(length=len(y_coordinates),
                                fitness_fn=fitness_dists,
                                maximize=False)
    return problem_fit
예제 #24
0
import mlrose
import numpy as np

# Create list of city coordinates
coords_list = [(0, 1), (3, 4), (6, 5), (7, 3), (15, 0), (12, 4), (14, 10),
               (9, 6), (7, 9), (0, 10)]

# Initialize fitness function object using coords_list
fitness_coords = mlrose.TravellingSales(coords=coords_list)

problem_fit = mlrose.TSPOpt(length=10,
                            fitness_fn=fitness_coords,
                            maximize=False)

best_state, best_fitness = mlrose.genetic_alg(problem_fit, random_state=2)

print('The best state found is: ', best_state)

print('The fitness at the best state is: ', best_fitness)
예제 #25
0
# fix: cannot import name 'six' from 'sklearn.externals' 
import six
import sys
sys.modules['sklearn.externals.six'] = six

import mlrose
import numpy as np

# Create list of city coordinates
coords_list = [(1, 1), (4, 2), (5, 2), (6, 4), (4, 4), (3, 6), (1, 5), (2, 3)]

# Initialize fitness function object using coords_list
fitness_coords = mlrose.TravellingSales(coords = coords_list)

# Create list of distances between pairs of cities
dist_list = [(0, 1, 3.1623), (0, 2, 4.1231), (0, 3, 5.8310), (0, 4, 4.2426), \
             (0, 5, 5.3852), (0, 6, 4.0000), (0, 7, 2.2361), (1, 2, 1.0000), \
             (1, 3, 2.8284), (1, 4, 2.0000), (1, 5, 4.1231), (1, 6, 4.2426), \
             (1, 7, 2.2361), (2, 3, 2.2361), (2, 4, 2.2361), (2, 5, 4.4721), \
             (2, 6, 5.0000), (2, 7, 3.1623), (3, 4, 2.0000), (3, 5, 3.6056), \
             (3, 6, 5.0990), (3, 7, 4.1231), (4, 5, 2.2361), (4, 6, 3.1623), \
             (4, 7, 2.2361), (5, 6, 2.2361), (5, 7, 3.1623), (6, 7, 2.2361)]

# Initialize fitness function object using dist_list
fitness_dists = mlrose.TravellingSales(distances = dist_list)

# Define optimization problem object
problem_fit = mlrose.TSPOpt(length = 8, fitness_fn = fitness_coords, maximize=False)

# Create list of city coordinates
coords_list = [(1, 1), (4, 2), (5, 2), (6, 4), (4, 4), (3, 6), (1, 5), (2, 3)]
예제 #26
0
def get_object_places(table_path, graph_path, visited_places):
    assert os.path.exists(table_path)
    assert os.path.exists(graph_path)

    df = pd.read_csv(table_path, index_col=0)

    while True:
        #speech to text part
        # obtain audio from the microphone
        r = sr.Recognizer()
        with sr.Microphone() as source:

            print("Quale oggetto stai cercando?\n")
            #audio = r.listen(source)

            # recognize speech using Google Cloud Speech
            try:
                object_to_search = "wallet"
                #object_to_search = r.recognize_google_cloud(audio, credentials_json=GOOGLE_CLOUD_SPEECH_CREDENTIALS).strip()

                #similar = check_similapr_objects(df, object_to_search)
                #print(similar)
                if (len(df.loc[df["object"] == object_to_search]) > 0):
                    break
                elif (similar != None):
                    answer = input(
                        object_to_search +
                        " non trovato, trovata compatibilita' con " + similar +
                        ", utilizzare la sua distribuzione?[Y/n]\n")
                    if (answer == "Y"):
                        object_to_search = similar
                        break

            except sr.UnknownValueError:
                print("Google Cloud Speech could not understand audio")
            except sr.RequestError as e:
                print(
                    "Could not request results from Google Cloud Speech service; {0}"
                    .format(e))

    df = df.loc[df["object"] == object_to_search].drop('object', 1)
    places = list(df.keys())

    #dropping places already visited

    for visited_place in visited_places:
        df = df.drop(visited_place, 1)
        places.remove(visited_place)

    row = df
    print(row)

    for x in list(zip(row.keys(), row.values[0])):
        print(str(x[0]) + " " + str(x[1]))

    knowledge = row.values[0]

    number_of_places = len(knowledge)

    distances_dict = get_distances(graph_path,
                                   ("pose", 1.7219, 11.1261, "storage"))
    distances = [distances_dict[key] for key in places]
    max_distance = max(distances)

    inverted_distances = list(
        map(lambda x: abs(x - max_distance + 1) / 5, distances))

    prior_knowledge = np.array(inverted_distances)

    with pm.Model() as model:
        # Parameters of the Multinomial are from a Dirichlet
        parameters = pm.Dirichlet('parameters',
                                  a=prior_knowledge,
                                  shape=number_of_places)
        # Observed data is from a Multinomial distribution
        observed_data = pm.Multinomial('observed_data',
                                       n=sum(knowledge),
                                       p=parameters,
                                       shape=number_of_places,
                                       observed=knowledge)

    with model:
        # Sample from the posterior
        trace = pm.sample(draws=1000,
                          chains=2,
                          tune=500,
                          discard_tuned_samples=True)

        trace_df = pd.DataFrame(trace['parameters'], columns=places)

    # For probabilities use samples after burn in
    pvals = trace_df.iloc[:, :number_of_places].mean(axis=0)
    tag_and_dist = sorted(zip(places, pvals), key=lambda x: x[1], reverse=True)
    display_probs(dict(tag_and_dist))

    top_4_places = [x[0] for x in tag_and_dist[:4]]

    g = build_graph(graph_path)

    topn_nodes = []

    for label in top_4_places:
        for node in g.nodes():
            _, _, _, node_label = node
            if (node_label == label):
                topn_nodes += [node]
                break

    #adding the actual position to the top4 nodes
    topn_nodes += [("pose", 7.3533, 0.5381, "corridor-1")]
    subgraph = nx.Graph()

    edges = list(itertools.combinations(g.subgraph(topn_nodes), 2))

    all_distances = dict(nx.all_pairs_shortest_path_length(g))

    edges_with_weight = [(topn_nodes.index(x[0]), topn_nodes.index(x[1]),
                          all_distances[x[0]][x[1]]) for x in edges]

    print(edges_with_weight)

    fitness_dists = mlrose.TravellingSales(distances=edges_with_weight)
    problem_fit = mlrose.TSPOpt(length=len(topn_nodes),
                                fitness_fn=fitness_dists,
                                maximize=False)
    best_state, best_fitness = mlrose.genetic_alg(problem_fit, random_state=2)

    path = [topn_nodes[x][3] for x in best_state]

    path = rotate(path, path.index('corridor-1'))

    print(path)
예제 #27
0
'''
SAME PROBLEM USING MLROSE LIBRARY
'''

import mlrose
# create a list of triplets (u,v,d) giving distance d between nodes u and v.
'''
assume
city-0,city-1,city-2,,city-3,city-4,city-5,city-6,city-7,city-8,city-9  
'''
dist_list = [(0, 1, 3.1623), (0, 2, 4.1231), (0, 3, 5.8310), (0, 4, 4.2426),
             (0, 5, 5.3852), (0, 6, 4.0000), (0, 7, 2.2361), (1, 2, 1.0000),
             (2, 6, 5.0000), (2, 7, 3.1623), (3, 4, 2.0000), (3, 5, 3.6056),
             (3, 6, 5.0990), (3, 7, 4.1231), (4, 5, 2.2361), (4, 6, 3.1623),
             (4, 7, 2.2361), (5, 6, 2.2361), (5, 7, 3.1623), (6, 7, 2.2361)]

coords_list = [(1, 1), (4, 2), (5, 2), (6, 4), (4, 4), (3, 6), (1, 5), (2, 3)]

fitness_func = mlrose.TravellingSales(distances=dist_list)
optimization_problem = mlrose.TSPOpt(length=8,
                                     fitness_fn=fitness_func,
                                     maximize=False,
                                     distances=dist_list)
init_state = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])  # Define initial state
best_state, best_fitness = mlrose.genetic_alg(optimization_problem,
                                              pop_size=1000,
                                              mutation_prob=0.07,
                                              random_state=2)

print('The best state : ', best_state)
print('Fitness: ', best_fitness)
예제 #28
0
def main():
    name_of_exp = "TSP"

    # Create list of city coordinates
    coords_list = [(1, 1), (4, 2), (5, 2), (6, 4), (4, 4), (3, 6), (1, 5), (2, 3)]

    # Initialize fitness function object using coords_list
    fitness_coords = mlrose.TravellingSales(coords=coords_list)
    problem = mlrose.TSPOpt(length=8, fitness_fn=fitness_coords,
                            maximize=False)

    # Define initial state
    x_s = []
    y_s = []
    z_s = ['RHC', 'SA', 'GA', 'MIMIC']
    w_s = []
    max_val = 19.0
    found_flag = False
    for restarts in np.arange(0, 5):
        if found_flag:
            break
        for max_iter_atts in np.arange(10, 1000, 10):
            if found_flag:
                break
            # Solve problem using simulated annealing
            best_state, best_fitness, learning_curve, timing_curve = mlrose.random_hill_climb(problem, max_attempts=int(
                max_iter_atts), max_iters=int(max_iter_atts),
                                                                                              restarts=int(restarts),
                                                                                              curve=True,
                                                                                              random_state=1)
            if best_fitness <= max_val:
                x_s.append(np.arange(0, len(learning_curve)))
                y_s.append(learning_curve)
                w_s.append(timing_curve)
                print(best_state)
                print(best_fitness)
                print(max_iter_atts)
                print(restarts)
                found_flag = True

    found_flag = False
    for sched in [mlrose.ExpDecay(), mlrose.GeomDecay(), mlrose.ArithDecay()]:
        if found_flag:
            break
        for max_iter_atts in np.arange(10, 1000, 10):
            if found_flag:
                break
            best_state, best_fitness, learning_curve, timing_curve = mlrose.simulated_annealing(problem,
                                                                                                max_attempts=int(
                                                                                                    max_iter_atts),
                                                                                                max_iters=int(
                                                                                                    max_iter_atts),
                                                                                                schedule=sched,
                                                                                                curve=True,
                                                                                                random_state=1)
            if best_fitness <= max_val:
                x_s.append(np.arange(0, len(learning_curve)))
                y_s.append(learning_curve)
                w_s.append(timing_curve)
                print(best_state)
                print(best_fitness)
                print(max_iter_atts)
                print(sched)
                found_flag = True

    found_flag = False
    for prob in np.arange(0.1, 1.1, 0.1):
        if found_flag:
            break
        for pop_size in np.arange(100, 1000, 100):
            if found_flag:
                break
            for max_iter_atts in np.arange(100, 1000, 100):
                if found_flag:
                    break
                best_state, best_fitness, learning_curve, timing_curve = mlrose.genetic_alg(problem,
                                                                                            pop_size=int(pop_size),
                                                                                            mutation_prob=prob,
                                                                                            max_attempts=int(
                                                                                                max_iter_atts),
                                                                                            max_iters=int(
                                                                                                max_iter_atts),
                                                                                            curve=True,
                                                                                            random_state=1)
                if best_fitness <= max_val:
                    x_s.append(np.arange(0, len(learning_curve)))
                    y_s.append(learning_curve)
                    w_s.append(timing_curve)
                    print(best_state)
                    print(best_fitness)
                    print(max_iter_atts)
                    print(prob)
                    print(pop_size)
                    found_flag = True

    found_flag = False
    for prob in np.arange(0.1, 0.5, 0.1):
        if found_flag:
            break
        for pop_size in np.arange(100, 1000, 100):
            if found_flag:
                break
            for max_iter_atts in np.arange(100, 1000, 100):
                if found_flag:
                    break
                best_state, best_fitness, learning_curve, timing_curve = mlrose.mimic(problem, pop_size=int(pop_size),
                                                                                      keep_pct=prob,
                                                                                      max_attempts=int(max_iter_atts),
                                                                                      max_iters=int(max_iter_atts),
                                                                                      curve=True,
                                                                                      random_state=1,
                                                                                      fast_mimic=True)
                if best_fitness <= max_val:
                    x_s.append(np.arange(0, len(learning_curve)))
                    y_s.append(learning_curve)
                    w_s.append(timing_curve)
                    print(best_state)
                    print(best_fitness)
                    print(max_iter_atts)
                    print(prob)
                    print(pop_size)
                    found_flag = True

    for x, y, z in zip(x_s, y_s, z_s):
        plt.plot(x, y, label=z)
    plt.legend()
    plt.title('Randomized Optimization Iterations vs Fitness Function Value for {}'.format(name_of_exp))
    plt.xlabel('Function iteration count')
    plt.ylabel('Fitness function value')
    plt.show()
    plt.clf()
    for x, w, z in zip(x_s, w_s, z_s):
        plt.plot(x, w, label=z)
    plt.legend()
    plt.title('Randomized Optimization Time vs Fitness Function Value for {}'.format(name_of_exp))
    plt.xlabel('Function iteration count')
    plt.ylabel('Time in Seconds')
    plt.show()
예제 #29
0
def TSP(places_to_visit, duration, dailyDriveTime):
    print('start distance matrix')

    distance_matrix = createDistanceMatrix(places_to_visit)

    print('distance matrix done')
    print(distance_matrix)

    fitness = mlrose.TravellingSales(distances=distance_matrix)
    # We want to visit all the places of our list "places_to_visit"
    problem = mlrose.TSPOpt(length=len(places_to_visit),
                            fitness_fn=fitness,
                            maximize=False)
    best_state, best_fitness = mlrose.genetic_alg(problem,
                                                  random_state=0,
                                                  pop_size=300,
                                                  mutation_prob=0.3)

    print('melrose done')
    print('best_state', best_state)
    print('best_fitness', best_fitness)

    max_time = duration * dailyDriveTime * 60 * 60
    dailyDriveTime = dailyDriveTime * 60 * 60

    print('max_time', max_time)
    print('dailyDriveTime', dailyDriveTime)

    final_itin = []
    for day in range(duration):
        final_itin.append([])

    print('empty final itin done')
    print(final_itin)

    day = 0
    current_time = 0

    for idx, place_idx in enumerate(best_state[:-1]):
        travelTime = findDistance(best_state[idx], best_state[idx + 1],
                                  distance_matrix)
        # add to current day
        if current_time + travelTime < dailyDriveTime:
            final_itin[day].append(place_idx)
            current_time += travelTime
        # add to next day
        elif day + 1 < len(final_itin):
            day += 1
            final_itin[day].append(place_idx)
            current_time = travelTime
        # end, cant add any more destinations

        # print('At idx ', idx)
        # print('We are on day: ', day)
        # print('travel_time: ', travelTime)
        # print('current_time', current_time)

    print('Final Itin - split over days done')
    print(final_itin)

    final_itin_idxs = copy.deepcopy(final_itin)

    itin_final = orderPlaces(places_to_visit, final_itin)

    print('--- Final Itin DONE ---')
    print(itin_final)

    return itin_final, final_itin_idxs
예제 #30
0
    plt.title("Convergence curve: TSP-Qatar using Simulated Annealing")
    plt.xlabel("Iterations")
    plt.ylabel("Fitness")
    plt.savefig("tsp_qatar_sa.png")


if __name__ == "__main__":

    # Reading data
    tsp = tsplib95.load('qa194.tsp')
    tsp_data = tsp.as_name_dict()
    # print("##### Data #####\n")
    # print(tsp_data)
    # print("\n")

    # Getting the city coordinates
    cities = [tsp_data['node_coords'][k] for k in tsp_data['node_coords']]

    # Initialize fitness function object using coordinates
    fitness_coords = mlrose.TravellingSales(coords=cities)

    # Define optimization problem object
    problem_fit = mlrose.TSPOpt(length=len(cities),
                                fitness_fn=fitness_coords,
                                maximize=False)

    print("###### Solving using Genetic Algorithm ######\n")
    solve_ga(problem_fit)
    print("###### Solving using Simulated Annealing Algorithm ######\n")
    solve_sa(problem_fit)