def predict(self, sent, unit, feats): score = self.__get_scores_for_MST(sent, unit, self.model, self.model.map_feature, feats) graph = MST(score) sent.add_unitheads(graph.edges()) # use to check unit accuracy # sent.add_heads(graph.edges()) return sent
def heuristic_multi_goal(curr_child, goal_list, path_cost, temp_cost, closed_list, heu_val): dist_2goal = np.zeros(len(goal_list)) i = 0 for goal in goal_list: dist_2goal[i] = util.heuristicFcn(curr_child, goal) i += 1 min_dist_2goal = np.amin(dist_2goal) list = [curr_child] list.extend(goal_list) tree = MST.maze2tree(goal_list) min_tree = minimum_spanning_tree(tree, overwrite=False) min_tree = min_tree.toarray().astype(int) MSTweight = MST.findMSTweight(min_tree) heuristic = MSTweight + min_dist_2goal + temp_cost if (closed_list == 0) or (heuristic < heu_val): hn = heuristic cost = path_cost + 1 flag = 1 else: hn = heu_val cost = 0 flag = 0 return flag, hn, cost
def main(): algorithm: str = "" if len(argv) < 2: print('Not enough arguments!') print('Usage: main (-k|-p)') return elif argv[1] == '-k': algorithm = KRUSKAL elif argv[1] == "-p": algorithm = PRIM else: print('Unknown algorithm') return n: int = 0 try: n = int(stdin.readline()) except ValueError: print("Wrong \'n\' input format") return G: Graph = Graph(n, directed=False) m: int = 0 try: m = int(stdin.readline()) except ValueError: print("Wrong \'m\' input format") return try: for _ in range(m): line = stdin.readline() u, v, w = getEdge(line) edge = Edge(u, v, w) G.add_edge(edge) except ValueError: print("Wrong \'u v w\' input format") return mst: List[Edge] = None weight: float = 0 if algorithm == KRUSKAL: mst, weight = MST.kruskal(G) elif algorithm == PRIM: mst, weight = MST.prim(G, 1) else: raise Exception('Unsupported algorithm') for e in mst: fst, snd, w = e.unpack() u, v = (fst, snd) if fst < snd else (snd, fst) print(u, v, w) print(weight)
def __call__(self, v): """ @param v: a vector @return: the cost of this vector """ n = len(self.z_points) assert len(v) == 2*n # first split v into its two constituent vectors va, vb = v[:n], v[n:] # get the augmented list of points augmented_points = self.z_points + [va, vb] # get the distance matrix distance_matrix = get_euclidean_distance_matrix(augmented_points) # define the vertices of the graph V = range(len(augmented_points)) # define the weighted edges of the graph E = [] for i in range(len(distance_matrix)): for j in range(len(distance_matrix)): if i < j: distance = distance_matrix[i][j] weight = distance ** 2 edge = (weight, i, j) E.append(edge) # find the minimum spanning tree T = MST.kruskal(V, E) # find the total weight of the minimum spanning tree total_weight = sum(weight for weight, a, b in T) # track the best found so far state = (total_weight, T) if self.best is None: self.best = state self.best = min(self.best, state) # return the total weight that we want minimized return total_weight
def getEdgeRobustness(Graph): new = mst.Graph(Graph.V) new.graph = Graph.graph new.r = mRE.randomConnections(new, 1) efficiency = [] while True: try: new.dist() efficiency.append(eff.getEfficiency(new)) new.newConnection(1, 0) except IndexError: return mean(efficiency)
def main(): #Gets User input initial, groups = get_user_input() #, totalnodes, inc #Creates Plots according to user inputs numPlots = 1 #int(((totalnodes - initial)/inc)) + 1 fig, axs = plt.subplots(numPlots, sharex=True) fig.suptitle('Efficiency vs Edges at nodes') i = 0 #Loops user inputs so creates n starting points with nodes, for num1 in range(initial, initial + 1, 1): #totalnodes + 1, inc): g = mst.Graph(num1) g.newMST() edges = int((num1 * (num1 - 1)) / 2 - (num1 - 1)) + 1 interval = int(float(edges) * float(groups / 100)) Data = { 'Edges': list(range(1, edges, interval)), 'Efficiency': [], 'Efficiency Alt': [], # 'Network Connectivity': [], # 'Robustness': [], # 'Edge Robustness': [] } add_Network_Data(g, Data, interval) df = pd.DataFrame( Data, columns=[ 'Edges', 'Efficiency', 'Efficiency Alt', # 'Network Connectivity', 'Robustness', # 'Edge Robustness' ]) name = 'Nodes=' + str(num1) create_Graph(numPlots, axs, i, df, name) create_dataframe_folder(df, name) i += 1 #Shows final plot if len(sys.argv) > 1: plt.show()
def run(G: Graph) -> Result: c: Counter = Counter() mst, _ = MST.prim(G, 1) # mst, _ = MST.kruskal(G) Tree = Graph(G.N, directed=False) Tree.add_edges(mst) visited: List[bool] = [False for _ in range(G.N + 1)] walk: List[int] = [] def DFS(u: int): visited[u] = True walk.append(u) c.inc() for e in Tree.get_incident_edges(u): v = e.snd if not visited[v]: DFS(v) DFS(1) path: List[Edge] = [] W: float = 0.0 first: int = walk[0] u: int = first walk.append(first) for v in walk[1:]: c.inc() e = G.get_edge(u,v) path.append(e) W += e.w u = v memory: int = 0 memory += sizeof(mst) memory += sizeof(Tree) memory += sizeof(visited) memory += sizeof(walk) return Result(c.get(), W, memory, path=path)
def get_mst(query_edges, allpoints): """ Return a sublist of the query edges which forms a minimum spanning tree. @param query_edges: point index pairs @param allpoints: ordered points as pairs of coordinates @return: minimum spanning tree edges """ # get the point indices occurring in at least one query edge V = list(sorted(set(itertools.chain.from_iterable(query_edges)))) # get the weighted edges E = [] for edge in query_edges: ax, ay = allpoints[edge[0]] bx, by = allpoints[edge[1]] weight = math.hypot(bx - ax, by - ay) E.append((weight, edge[0], edge[1])) # get the minimum spanning tree weighted edges E_mst = MST.kruskal(V, E) # get the minimum spanning tree edges return [(va, vb) for w, va, vb in E_mst]
def inference(self, test_set, real_test, golden_set): correct = 0 total = 0 result_dict = {} for sentence in test_set: graph_with_all_weights = self.feature_maker.create_weighted_graph_for_sentence( sentence, self.weights, test_set) maximum_spanning_tree = mst.mst(0, graph_with_all_weights) if not real_test: golden_standard = golden_set[sentence] correct += self.number_of_correct(maximum_spanning_tree, golden_standard) total += (len(test_set[sentence]) - 1) accuracy = float(float(correct) / total) else: result_dict[sentence] = maximum_spanning_tree if not real_test: print("The final accuracy is ", accuracy, " achieved with ", self.global_iterations, " iterations") return accuracy else: return result_dict
def run(self): self.init_weights() begin = time.time() problem = 0 for iteration in range(0, self.global_iterations): for sentence in self.feature_maker.train_data: graph_with_all_weights = self.feature_maker.create_weighted_graph_for_sentence( sentence, self.weights, self.feature_maker.train_data) maximum_spanning_tree = mst.mst(0, graph_with_all_weights) """if 0 not in maximum_spanning_tree: maximum_spanning_tree = self.connect_tree(maximum_spanning_tree)""" golden_standard = self.feature_maker.golden_standard[sentence] if not self.compare_trees(maximum_spanning_tree, golden_standard): self.add(self.feature_maker. sentence_feature_dictionary[sentence]) self.subtract( self.feature_maker.create_feature_vector_from_tree( sentence, maximum_spanning_tree)) print("perceptron run took :", time.time() - begin, " with ", self.global_iterations, " iterations") print("problem with ", problem) return self.weights
def replanning(original_graph, virtual_graph, list_of_H): PolC = original_graph['PolC'] colors_0 = ['b', 'r', 'g', 'y'] # 'change_plan' is True if the new plan is better than the old one change_plan = False R = len(list_of_H) list_of_robs = [] for r in range(R): list_of_robs.append(list_of_H[r].id) id = min(list_of_robs) #id of the robot that is computing the replan speeds = [] search_speeds = [] colors = [] for r in range(R): #exec ('H%d = list_of_H[%d]' % (r, r)) #exec ('speeds.append(H%d.specs[0])' % r) #exec ('search_speeds.append(H%d.specs[1])' % r) #exec ('colors.append(colors_0[H%d.id])' % r) speeds.append(list_of_H[r].specs[0]) search_speeds.append(list_of_H[r].specs[1]) colors.append(colors_0[list_of_H[r].id]) old_cost = myLib.get_cost(original_graph, list_of_H, speeds, search_speeds) set_uv, set_v, set_g, pts = define_subsets(list_of_H, virtual_graph) print '\nHere is set_v (visited edges) in original inedexes:' print set_v print 'Here is set_uv (unvisited edges) in original inedexes:' print set_uv print 'Here is set_g (assigned edges) in original inedexes:' print set_g, '\n\n' # Map the unvisited nodes with new labels C = virtual_graph['Ccom'] #matrix with the length costs Cuv = np.matrix( C ) # Reduced cost matrix with only the unvisited edges (unvisited virtual nodes) C = virtual_graph['C_sp'] #matrix with the number of search points Cuv_sp = np.matrix( C ) # Reduced cost matrix with only the unvisited edges (unvisited virtual nodes) #exclude_list = (np.array(set_v) - 1).tolist() exclude_list = (np.array(set_v) - 1).tolist() + (np.array(set_g) - 1).tolist() Cuv = np.delete(Cuv, exclude_list, 0) # exclude lines Cuv = np.delete(Cuv, exclude_list, 1) # exclude columns Cuv = Cuv.tolist() Cuv_sp = np.delete(Cuv_sp, exclude_list, 0) # exclude lines Cuv_sp = np.delete(Cuv_sp, exclude_list, 1) # exclude columns Cuv_sp = Cuv_sp.tolist() # Define the depot virtual nodes for the task assignment depots = [] for r in range(R): #exec ('depots.append(set_uv.index(H%d.currEdge))' % r) depots.append(set_uv.index(list_of_H[r].currEdge)) print '\nHere is depot virtual nodes (new indexes):' print depots print 'Here is depot virtual nodes (original indexes):' depots_ori = [] #original depot points?? for r in range(R): depots_ori.append(set_uv[depots[r]]) print depots_ori, '\n' print '\n ----- Task assignment function called -----' #[sol, C_check0, C_check1] = TA.execute_lp(speeds, search_speeds, depots, colors, Cuv, Cuv_sp, pts) sol = TA.execute_lp(speeds, search_speeds, depots, colors, Cuv, Cuv_sp, pts) #print "Here is the solution of the TA problem: \n", sol # ---------- ---------- ---------- ---------- ---------- ---------- ---------- # Map the solution back to the original indexes n_uv = len(Cuv) m_uv = n_uv * (n_uv - 1) x_var = [] for r in range(R): #exec ('x%d_var = []' % r) x_var.append([]) F_var = sol.pop() for r in range(R): for k in range(m_uv): #exec ('x%d_var.insert(0,sol.pop())' % (R - r - 1)) x_var[R - r - 1].insert(0, sol.pop()) division = [] for r in range(R): division.append([]) k = -1 for i in range(n_uv): for j in range(n_uv): if i != j: k = k + 1 for r in range(R): #exec ('xAux_var = x%d_var' % r) xAux_var = x_var[r] if (xAux_var[k] == 1): division[r].append(i) division[r].append(j) for r in range(R): division[r] = list(set(division[r])) #Map the nodes back to the original indexation for r in range(R): for k in range(len(division[r])): division[r][k] = set_uv[division[r][k]] print '\nAssigned edges for the robots: (before excluding the current edges)' for r in range(R): print 'Subset for robot ' + str(list_of_H[r].id) + ': ', division[r] print '\n' # Exclude/Remove the used depot virtual nodes (they are edges that were already visited) for r in range(R): print 'division[r]', division[r] print 'division[r].index(list_of_H[r].currEdge)', division[r].index( list_of_H[r].currEdge) division[r].pop(division[r].index(list_of_H[r].currEdge)) # Include the used depot virtual nodes in the visited set for r in range(R): set_v.append(list_of_H[r].currEdge) print '\nAssigned edges for the robots:' for r in range(R): print 'Subset for robot ' + str(list_of_H[r].id) + ': ', division[r] print '\n' # ---------- ---------- ---------- ---------- ---------- ---------- ---------- # Call MST for every robot in the communication graph in order to make the graph connected print '\n ----- Applying MST to the disconnected subgraphs ------' subgraphs = [] for r in range(R): subgraphs.append([]) #pylab.figure(100) pylab.figure(id) pylab.subplot(2, R, R + (r + 1)) subgraphs[r] = MST.MSTconnect(original_graph, division[r], (list_of_H[r]).nextNode, colors[r], True) for r in range(R): print 'Subset of edges for robot ' + str( r) + ': (original indexes)\n', subgraphs[r] print 'Start node for robot ' + str(r) + ':', (list_of_H[r]).nextNode # ---------- ---------- ---------- ---------- ---------- # Cal CPP for every graph generated by the MST based algorithm print '\nApplying CPP to the connected subgraphs' Hole_path_list = [] for r in range(R): Hole_path_list.append([]) current_node = (list_of_H[r]).nextNode edges_listOfTuples = myLib.write_listOfTuples(original_graph, subgraphs[r]) #Hole_path_list[r] = cppsolver.CPP(sorted(edges_listOfTuples), current_node) Hole_path_list[r] = CPPlib.main_CPP(sorted(edges_listOfTuples), current_node) #for k in range(R): print 'Route for robot ' + str(r), ': ', Hole_path_list[r] print '\n' # ---------- ---------- ---------- ---------- ---------- #Create list T_a pts_0 = virtual_graph['nodes'] T_a0 = [Intlist()] for k in range(len(PolC[0]) - 1): IL = Intlist() T_a0.append(IL) for k in range(len(pts_0)): T_a0[k].data = list(list_of_H[0].T_a[0].data) + list( list_of_H[1].T_a[1].data) T_a0[k].data = list(T_a0[k].data) if k + 1 in set_uv: # if in unvisite list if k + 1 in division[0]: # if in the assigned to the other one T_a0[k].data.append(list_of_H[0].id) elif k + 1 in division[1]: T_a0[k].data.append(list_of_H[1].id) T_a0[k].data = list(set(T_a0[k].data)) #Create list T_f T_f0 = [] for r in range(R): T_f0 = T_f0 + list(list_of_H[r].T_f) T_f0 = T_f0 + set_v T_f0 = list(set(T_f0)) # Create the new list of histories (STILL MUST ADAPT TO A GENERAL NUMBER OF ROBOS) new_Hists = [] for r in range(R): H = History() H.id = list_of_H[r].id H.e_v = set_v H.e_uv = division[r] for r2 in range(R): if r2 != r: H.e_g = division[r2] + set_g H.T_a = T_a0 H.T_f = T_f0 #print "\n\n----------------\n Here is T_f0:",T_f0, "\n----------------\n\n" H.lastMeeting = [] for r2 in range(R): H.lastMeeting.append(list_of_H[r2].id) H.Whole_path = Hole_path_list[r] new_Hists.append(H) new_cost = myLib.get_cost(original_graph, new_Hists, speeds, search_speeds) #print "\n\n-------------------\nHere is new_Hists[0].T_f", new_Hists[0].T_f, "\n-------------------\n\n" #print "\n\n-------------------\nHere is new_Hists[1].T_f", new_Hists[1].T_f, "\n-------------------\n\n" print 'Here is old cost: ', old_cost print 'Here is new cost: ', new_cost # Check if the new plan is better than the previous one change_plan = False if new_cost < old_cost: change_plan = True # Plot the disconnected graph # ---------- ---------- ---------- ---------- ---------- ---------- ---------- #pylab.figure(100) #pylab.figure(id) """ pylab.subplot(2, 2, 1) pylab.axis('equal') pylab.axis(virtual_graph['w_s']) pylab.title('MILP result for robot %d' % H0.id) pylab.subplot(2, 2, 2) pylab.axis('equal') pylab.axis(virtual_graph['w_s']) pylab.title('MILP result for robot %d' % H1.id) """ #Initialize the plot of the result of the TA algorithm for r in range(R): pylab.subplot(2, R, (r + 1)) pylab.axis('equal') pylab.axis(virtual_graph['w_s']) pylab.title('Task assig. robot %d' % list_of_H[r].id) for e in range(len(PolC[0])): [fr, to, cx, cy, cost] = myLib.getCoefs(e, PolC) p0 = [0.01 * k for k in range(101)] x = [] y = [] for p in p0: x.append(0) y.append(0) for k in range(6): # Compute refference position x[-1] = x[-1] + cx[6 - k - 1] * p**k y[-1] = y[-1] + cy[6 - k - 1] * p**k """ pylab.subplot(2, 2, 1) pylab.plot(x, y, 'k--', linewidth=1.0) pylab.subplot(2, 2, 2) pylab.plot(x, y, 'k--', linewidth=1.0) """ #Plot the the edge in the background for r in range(R): pylab.subplot(2, R, (r + 1)) #pylab.plot(x, y, 'k--', linewidth=1.0) pylab.plot(x, y, 'k-', linewidth=1.0) """ if e + 1 in division[0]: pylab.subplot(2, 2, 1) pylab.plot(x, y, colors[0], linewidth=3.0) if e + 1 in division[1]: pylab.subplot(2, 2, 2) pylab.plot(x, y, colors[1], linewidth=3.0) """ for r in range(R): if e + 1 in division[r]: pylab.subplot(2, R, (r + 1)) pylab.plot(x, y, colors[r], linewidth=3.0) # ---------- ---------- ---------- ---------- ---------- ---------- ---------- """ # Plotting the heuristic costs # ---------- ---------- ---------- ---------- ---------- ---------- ---------- for i in range(len(pts)): x = pts[i][0] y = pts[i][1] pylab.subplot(2, 2, 1) pylab.text(x, y, ("%.2f" % C_check0[i]), fontsize=8.0) pylab.subplot(2, 2, 2) pylab.text(x, y, ("%.2f" % C_check1[i]), fontsize=8.0) # ---------- ---------- ---------- ---------- --------- ---------- ---------- """ if not change_plan: print 'New cost is not better ...' print '---------- ---------- ---------- ---------- ---------- ---------- ---------- ----------' print '---------- ---------- ---------- APPLYING THE SIMPLE REPLAN ---------- ---------- ----------' print '---------- ---------- ---------- ---------- ---------- ---------- ---------- ----------' #OBS: This simple new plan is necessary. #If the new plan from MILP->MST->CPP is not better ok. However, we need to run CPP again because we have #division = [[],[]] division = [] for r in range(R): division.append([]) for r in range(R): for k in list_of_H[r].e_uv: if k in set_uv: division[r].append(k) print 'Here is new division (for the simple replan)' print division #Simple replan ---------- ---------- ---------- # Call MST for every robot in the communication graph in order to make the graph connected pylab.close() pylab.axis(virtual_graph['w_s']) print '\n ----- Applying MST to the disconnected subgraphs ------' subgraphs = [] for r in range(R): subgraphs.append([]) pylab.subplot(2, R, R + (r + 1)) print 'Here is new division (for the simple replan)' print division subgraphs[r] = MST.MSTconnect(original_graph, division[r], (list_of_H[r]).nextNode, colors[r], True) for r in range(R): print 'Subset of edges for robot ' + str( list_of_H[r].id) + ': (original indexes)\n', subgraphs[r] print 'Start node for robot ' + str(list_of_H[r].id) + ':', ( list_of_H[r]).nextNode # ---------- ---------- ---------- ---------- ---------- # Cal CPP for every graph generated by the MST based algorithm print '\nApplying CPP to the connected subgraphs' Hole_path_list = [] for r in range(R): Hole_path_list.append([]) current_node = (list_of_H[r]).nextNode edges_listOfTuples = myLib.write_listOfTuples( original_graph, subgraphs[r]) #Hole_path_list[r] = cppsolver.CPP(sorted(edges_listOfTuples), current_node) Hole_path_list[r] = CPPlib.main_CPP(sorted(edges_listOfTuples), current_node) #for r in range(R): print 'Route for robot ' + str( list_of_H[r].id), ': ', Hole_path_list[r] print '\n' # ---------- ---------- ---------- ---------- ---------- # Create the new list of histories (STILL MUST ADAPT TO A GENERAL NUMBER OF ROBOS) new_Hists = [] for r in range(R): H = History() H.id = list_of_H[r].id H.e_v = set_v H.e_uv = division[r] for r2 in range(R): if r2 != r: H.e_g = division[r2] + set_g H.T_a = T_a0 H.T_f = T_f0 H.lastMeeting = [] for r2 in range(R): H.lastMeeting.append(list_of_H[r2].id) H.Whole_path = Hole_path_list[r] new_Hists.append(H) # ---------- ---------- ---------- ---------- ---------- # Set the abort_curr_edge flag in te case to robots are in the same edge for r1 in range(R): for r2 in range(r1 + 1, R, 1): #This way r1<r2 if (list_of_H[r1].currEdge == list_of_H[r2].currEdge): new_Hists[r2].abort_curr_edge = True print '\nabort_curr_edge strategy:\nrob ', new_Hists[ r1].id, ' / rob ', new_Hists[r2].id, 'set flag' else: print '\nabort_curr_edge strategy:\nrob ', new_Hists[ r1].id, ' / rob ', new_Hists[r2].id # Set the abort_curr_edge flag in te case the edge was previously (thus, completely) visited by another robot #""" for r1 in range(R): for r2 in range(R): if (new_Hists[r1].currEdge in new_Hists[r2].e_v[0:-1]): new_Hists[r1].abort_curr_edge = True #""" # ---------- ---------- ---------- ---------- ---------- ---------- ---------- """ THE PROBLEM WITH THIS IS THAT THE MINIMUM ID ROBOT WILL KEEP SERACHING THE SPs THAT WERE ALREADY SEARCHED BY THE MAX ID ROBOT """ # Set the available flag as False for r in range(R): new_Hists[r].available = False # Save the result of TA and MST in a image import time hour = time.strftime("%Hh%Mm%Ss") date = time.strftime("d%dm%my%Y") rp = rospkg.RosPack() fig_name = rp.get_path('distributed') fig_name = fig_name + '/imagesResults/Results_' + date + '_' + hour + '.png' pylab.savefig(fig_name) # ---------- ---------- ---------- ---------- ---------- # Choose if the result of the planning will be platted or not SHOW_NEW_PLAN = True #SHOW_NEW_PLAN = False if SHOW_NEW_PLAN: pylab.show() pylab.close() return change_plan, Hole_path_list, new_Hists
def predict(self, sent, feats, factor = 1.0): score = self.__get_scores_for_MST(sent, self.model, self.model.map_feature, feats, factor) graph = MST(score) sent.add_heads(graph.edges()) return sent
def Astarsearch(graph, startpoint, start_time, time_dict, rest_list, place_to_rest, move_time, ptr_time): pq = PriorityQueue() n_nodes = len(graph.vertices()) mstCost = MST.mstCost(graph, [startpoint]) frontier = Frontier(mstCost, 0.0, [startpoint], startpoint, start_time) pq.put(frontier) found = False sequence = [startpoint] while (not found): curr = pq.get() if (len(curr.seq) == n_nodes and curr.eat_lunch == False and curr.eat_dinner == False): sequence = curr.seq cost = curr.prevCost + curr.mstCost break if (len(curr.seq) == n_nodes + 2 and curr.eat_lunch == True and curr.eat_dinner == True): sequence = curr.seq cost = curr.prevCost + curr.mstCost # print(sequence) # print(cost) #print(curr.cur_pathcost) break if (len(curr.seq) == n_nodes + 1 and curr.eat_dinner == True): # ate dinner sequence = curr.seq cost = curr.prevCost + curr.mstCost # print(sequence) # print(cost) #print(curr.cur_pathcost) break if (len(curr.seq) == n_nodes + 1 and curr.eat_lunch == True): sequence = curr.seq cost = curr.prevCost + curr.mstCost print(curr.cur_time) # print(cost) #print(curr.cur_pathcost) break if (curr.cur_time.time() >= dt.datetime.time( dt.datetime(100, 1, 1, 11, 00, 00)) and curr.cur_time.time() <= dt.datetime.time( dt.datetime(100, 1, 1, 13, 00, 00)) and not curr.eat_lunch): curr.eat_lunch = True findrest(rest_list, curr, pq, 0, place_to_rest, ptr_time) continue if (curr.cur_time.time() >= dt.datetime.time( dt.datetime(100, 1, 1, 17, 00, 00)) and curr.cur_time.time() <= dt.datetime.time( dt.datetime(100, 1, 1, 20, 00, 00)) and not curr.eat_dinner): curr.eat_dinner = True findrest(rest_list, curr, pq, 1, place_to_rest, ptr_time) continue # put restaurant into the frontier and do the other loop. adj_edges = graph.get_edges(curr.cur_vertex) # get all the adj edges. new_visited = [] for vertex in curr.seq: new_visited.append(vertex) for edge in adj_edges: cur_visit = [] for vertex in new_visited: cur_visit.append(vertex) if edge.dest not in cur_visit: cur_visit.append(edge.dest) time = timeadder( time_dict[edge.dest] + int(move_time[(curr.cur_vertex, edge.dest)]), curr.cur_time) cur_mstCost = MST.mstCost(graph, cur_visit) frontier = Frontier(cur_mstCost, curr.prevCost + float(edge.weight), cur_visit, curr.cur_vertex, time, curr.eat_lunch, curr.eat_dinner) pq.put(frontier) return sequence
def main(): # defining initial population pop = toolbox.MST_pop(n=nDisks) # clean up old files if os.path.exists('./stoppingRate.txt'): os.remove('stoppingRate.txt') if os.path.exists('./highEElectrons.txt'): os.remove('highEElectrons.txt') # clean up old result directories shutil.rmtree('runOutput', ignore_errors=True) print('Cleared run output') shutil.rmtree('evalOut', ignore_errors=True) print("Cleared evaluation output") # making new directories if not os.path.exists('./runOutput'): os.mkdir("./runOutput/") if not os.path.exists('./evalOut'): os.mkdir("./evalOut") print("-- Generation 1 --") # creating SIMG4 directory for the first iteration simG4Dir = '/vols/comet/users/sy5118/newBuild/OfflineProject/packages/SimG4/geometry_macros/GA_MST/generated_MST1' if not os.path.exists(simG4Dir): os.makedirs(simG4Dir) j = 0 for mst in pop: baby_MST = MST(nDisksOnAxis, mst, gen=1, id=j) baby_MST.write_MST(simG4Dir, j) j = j + 1 fitnesses = list( map(toolbox.evaluate, np.ones(nDisks), range(1, nDisks + 1))) storage = np.array([pop[1]]) for ind, fit in zip(pop, fitnesses): ind.fitness.values = fit # CXPB is the probability with which two individuals # are crossed # # MUTPB is the probability for mutating an individual CXPB, MUTPB = 0.5, 0.2 # Extracting all the fitnesses of fits = [ind.fitness.values[0] for ind in pop] # counter g = 1 # Begin the evolution while max(fits) < 1 and g < 5: g = g + 1 # A new generation simG4Dir = '/vols/comet/users/sy5118/newBuild/OfflineProject/packages/SimG4/geometry_macros/GA_MST/generated_MST' + str( g) if not os.path.exists(simG4Dir): os.makedirs(simG4Dir) print("-- Generation %i --" % g) # Select the next generation individuals offspring = toolbox.select(pop, len(pop)) # Apply crossover and mutation on the offspring for child1, child2 in zip(offspring[::2], offspring[1::2]): if random.random() < CXPB: toolbox.mate(child1, child2) del child1.fitness.values del child2.fitness.values for mutant in offspring: if random.random() < MUTPB: toolbox.mutate(mutant) del mutant.fitness.values j = 1 for pop in offspring: baby_MST = MST(nDisksOnAxis, pop, gen=g, id=j) baby_MST.write_MST(simG4Dir, j) pop.fitness.values = toolbox.evaluate(g, j) j = j + 1 # Clone the selected individuals offspring = list(map(toolbox.clone, offspring)) # Evaluate the individuals with an invalid fitness invalid_ind = [ind for ind in offspring if not ind.fitness.valid] fitnesses = map(toolbox.evaluate, invalid_ind) for ind, fit in zip(invalid_ind, fitnesses): ind.fitness.values = fit pop = offspring # Gather all the fitnesses in one list and print the stats fits = [ind.fitness.values[0] for ind in pop]
def exit(): root.destroy() MST.GeneticAlgorithm(15, 500, obstacle)
draw[0][1], draw[len(draw) - 1][0], draw[len(draw) - 1][1], fill="grey", width=3) root.after(500, exit) # root.bind('<3>', polygon) def exit(): root.destroy() MST.GeneticAlgorithm(15, 500, obstacle) root = tk.Tk() points = MST.getPoints() canvas = tk.Canvas(root, width=1000, height=1000) canvas.pack() canvas.old_coords = None for x, y in points: canvas.create_oval((10 * x) - 5, 1000 - (10 * y) - 5, (10 * x) + 5, 1000 - (10 * y) + 5, fill="blue", outline="blue", width=1) root.bind('<Button-1>', myfunction) root.bind('<Button-3>', polygon) root.mainloop()
#animate the genetic algorithm learning by graphing the best genome generation by generation #no obstacle implementation (can add obstacles in the animateMST) import matplotlib.pyplot as plt import matplotlib.animation as animation import MST NUMBER_OF_GENERATIONS = 500 NUMBER_OF_GENOMES = 20 intervalnumber = 0 MST.GeneticAlgorithm(NUMBER_OF_GENOMES, NUMBER_OF_GENERATIONS) points = MST.getPoints() mst = MST.returnMST() listofgenomes = MST.returnGenomes() fig = plt.figure() ax1 = fig.add_subplot(1, 1, 1) ax1.autoscale(False) ax1.set(xlim=(0, 110), ylim=(0, 110)) def animate(i): ax1.clear() global intervalnumber if (intervalnumber < 10): for x, y in points: ax1.scatter(x, y, c="black") elif (intervalnumber < 15): for x, y in points: ax1.scatter(x, y, c="black") for b in mst.path:
def plot(time, generation, allBestFitness, finalPath, firstPath, obstacle): fig, (ax1, ax2, ax3) = plt.subplots(3) ax2.autoscale(False) ax3.autoscale(False) ax2.set(xlim=(0, 110), ylim=(0, 110)) ax3.set(xlim=(0, 110), ylim=(0, 110)) a = ((firstPath.fitness - finalPath.fitness) / firstPath.fitness) * 100 if (a <= 0): a = 0.00000000001 fig.suptitle('Genetic MSP Results'.format(time)) ax1.set_title("Calculation Time: {0} seconds Improvement: {1}%".format( time, round_sig(a, 4)), fontsize=10) ax1.plot(range(0, generation), allBestFitness, c="green") # old_coords = None # for x,y in obstacle: # ax2.scatter(x,y,c="red") # ax3.scatter(x,y,c="red") # if old_coords: # x1,y1 = old_coords # ax3.plot([x,x1],[y,y1],'k-',color='red') # ax2.plot([x,x1],[y,y1],'k-',color='red') # old_coords = (x,y) for x, y in finalPath.chromosomes: ax3.scatter(x, y, c="blue") for x, y in firstPath.chromosomes: ax2.scatter(x, y, c="black") ax3.scatter(x, y, c="black") for a in firstPath.path: x1 = firstPath.chromosomes[a[0]][0] y1 = firstPath.chromosomes[a[0]][1] x2 = firstPath.chromosomes[a[1]][0] y2 = firstPath.chromosomes[a[1]][1] if (MST.collide([x1, y1], [x2, y2])): ax2.plot([x1, x2], [y1, y2], 'k-', color='orange') else: ax2.plot([x1, x2], [y1, y2], 'k-') ax2.set_title("Generation: {0} Start Fitness: {1}".format( 0, round_sig(firstPath.fitness, 5)), fontsize=10) for a in finalPath.path: x1 = finalPath.chromosomes[a[0]][0] y1 = finalPath.chromosomes[a[0]][1] x2 = finalPath.chromosomes[a[1]][0] y2 = finalPath.chromosomes[a[1]][1] if (MST.collide([x1, y1], [x2, y2])): ax3.plot([x1, x2], [y1, y2], 'k-', color='orange') else: ax3.plot([x1, x2], [y1, y2], 'k-') ax3.set_title("Generation: {0} Best Fitness: {1}".format( generation, round_sig(finalPath.fitness, 5)), fontsize=10) if (len(obstacle) > 0): obstacle.append( obstacle[0]) #repeat the first point to create a 'closed loop' xs, ys = zip(*obstacle) #create lists of x and y values ax3.plot(xs, ys, color='grey') ax2.plot(xs, ys, color='grey') fig.tight_layout() plt.show()
import distances import cities import MST distances = distances.get_distances() cities = cities.get_cities() vertices = len(distances) graph = MST.Graph(vertices) for city, endpoints in distances.items(): for city2 in endpoints: graph.add_edge(city2['start_id'], city2['end_id'], city2['distance']) result, cost = graph.MST() print ("Edges of MST") for u, v, weight in result: print("%s <-> %s = ~%d km" % (cities[u]['name'], cities[v]['name'], weight)) print("Total Cost => " , cost)
from k_means import * from convex_hull import * N = 10000 # points quantity sample_N = 100 # points for testing data K = 2 # clusters amount mass = [] edges = [] mst = [] center = [[130, 125], [700, 300]] # test centers of generated clusters gen = data_gen(center, N, K) # data generator dr = data_drawer(K) ch = convex_hull() m = MST(100, K) #mass = gen.normal_gen() #mass = gen.nested_data() mass = gen.get_random_data() # all points #mass = gen.get_real_random_data() #mass = gen.strip_data() sample = mass[:sample_N] smpl = data_gen(center, sample_N, K) smpl.mass = sample s_edges = smpl.get_edges() s_edges.sort() mst = m.get_MST(s_edges) km_obj = k_means(mass, K) #mass = gen.strip_data() #convex = ch.convex_hull(result[0]) #dr.draw_MST(mst, mass)
def DRL_implementation(filename, globali): try: # Filename corresponds to benchmark to route # filename = '3d.txt' # filename = '8by8small.gr' # 8-by-8 10 nets toy sample # filename = '8by8simplee.gr' # 8-by-8 10 nets toy sample # filename = 'adaptecSmall.gr' # filename = '4by4small.gr' # 3-by-3 nets toy sample # filename = '4by4simple.gr' # 3-by-3 nets toy sample # filename = 'adaptec1.capo70.2d.35.50.90.gr' # # Getting Net Info grid_info = init.read(filename) gridParameters = init.gridParameters(grid_info) # # GridGraph graphcase = graph.GridGraph(init.gridParameters(grid_info)) capacity = graphcase.generate_capacity() # print ('capacity before route: ',capacity.shape) gridX, gridY, gridZ = graphcase.generate_grid() # Real Router for Multiple Net # Note: pinCoord input as absolute length coordinates gridGraphSearch = twoPinASearch.AStarSearchGraph( gridParameters, capacity) # Sort net halfWireLength = init.VisualGraph( init.gridParameters(grid_info)).bounding_length() # print('Half Wire Length:',halfWireLength) sortedHalfWireLength = sorted(halfWireLength.items(), key=operator.itemgetter(1), reverse=True) # Large2Small # sortedHalfWireLength = sorted(halfWireLength.items(),key=operator.itemgetter(1),reverse=False) # Small2Large netSort = [] for i in range(gridParameters['numNet']): order = int(sortedHalfWireLength[i][0]) netSort.append(order) # random order the nets # print('netSort Before',netSort) # random.shuffle(netSort) # print('netSort After',netSort) routeListMerged = [] routeListNotMerged = [] # Getting two pin list combo (For RL) twopinListCombo = [] twopinListComboCleared = [] for i in range(len(init.gridParameters(grid_info)['netInfo'])): netNum = i netPinList = [] netPinCoord = [] for j in range(0, gridParameters['netInfo'][netNum]['numPins']): pin = tuple([ int((gridParameters['netInfo'][netNum][str(j + 1)][0] - gridParameters['Origin'][0]) / gridParameters['tileWidth']), int((gridParameters['netInfo'][netNum][str(j + 1)][1] - gridParameters['Origin'][1]) / gridParameters['tileHeight']), int(gridParameters['netInfo'][netNum][str(j + 1)][2]), int(gridParameters['netInfo'][netNum][str(j + 1)][0]), int(gridParameters['netInfo'][netNum][str(j + 1)][1]) ]) if pin[0:3] in netPinCoord: continue else: netPinList.append(pin) netPinCoord.append(pin[0:3]) twoPinList = [] for i in range(len(netPinList) - 1): pinStart = netPinList[i] pinEnd = netPinList[i + 1] twoPinList.append([pinStart, pinEnd]) twoPinListVanilla = twoPinList # Insert Tree method to decompose two pin problems here twoPinList = tree.generateMST(twoPinList) # print('Two pin list after:', twoPinList, '\n') # Remove pin pairs that are in the same grid nullPairList = [] for i in range(len(twoPinListVanilla)): if twoPinListVanilla[i][0][:3] == twoPinListVanilla[i][1][:3]: nullPairList.append(twoPinListVanilla[i]) for i in range(len(nullPairList)): twoPinListVanilla.reomove(nullPairList[i]) # Remove pin pairs that are in the same grid nullPairList = [] for i in range(len(twoPinList)): if twoPinList[i][0][:3] == twoPinList[i][1][:3]: nullPairList.append(twoPinList[i]) for i in range(len(nullPairList)): twoPinList.reomove(nullPairList[i]) # Key: use original sequence of two pin pairs twopinListComboCleared.append(twoPinListVanilla) # print('twopinListComboCleared',twopinListComboCleared) twoPinEachNetClear = [] for i in twopinListComboCleared: num = 0 for j in i: num = num + 1 twoPinEachNetClear.append(num) # print('twoPinEachNetClear',twoPinEachNetClear) for i in range(len(init.gridParameters(grid_info)['netInfo'])): netNum = int(sortedHalfWireLength[i][0]) # i # Sort the pins by a heuristic such as Min Spanning Tree or Rectilinear Steiner Tree netPinList = [] netPinCoord = [] for j in range(0, gridParameters['netInfo'][netNum]['numPins']): pin = tuple([ int((gridParameters['netInfo'][netNum][str(j + 1)][0] - gridParameters['Origin'][0]) / gridParameters['tileWidth']), int((gridParameters['netInfo'][netNum][str(j + 1)][1] - gridParameters['Origin'][1]) / gridParameters['tileHeight']), int(gridParameters['netInfo'][netNum][str(j + 1)][2]), int(gridParameters['netInfo'][netNum][str(j + 1)][0]), int(gridParameters['netInfo'][netNum][str(j + 1)][1]) ]) if pin[0:3] in netPinCoord: continue else: netPinList.append(pin) netPinCoord.append(pin[0:3]) twoPinList = [] for i in range(len(netPinList) - 1): pinStart = netPinList[i] pinEnd = netPinList[i + 1] twoPinList.append([pinStart, pinEnd]) # Insert Tree method to decompose two pin problems here twoPinList = tree.generateMST(twoPinList) # print('Two pin list after:', twoPinList, '\n') # Remove pin pairs that are in the same grid nullPairList = [] for i in range(len(twoPinList)): if twoPinList[i][0][:3] == twoPinList[i][1][:3]: nullPairList.append(twoPinList[i]) for i in range(len(nullPairList)): twoPinList.reomove(nullPairList[i]) # Key: Use MST sorted pin pair sequence under half wirelength sorted nets twopinListCombo.append(twoPinList) # print('twopinListCombo',twopinListCombo) # for i in range(1): for i in range(len(init.gridParameters(grid_info)['netInfo'])): # Determine nets to wire based on sorted nets (stored in list sortedHalfWireLength) # print('*********************') # print('Routing net No.',init.gridParameters(grid_info)['netInfo'][int(sortedHalfWireLength[i][0])]['netName']) # (above output is to get actual netName) # print('Routing net No.',sortedHalfWireLength[i][0]) netNum = int(sortedHalfWireLength[i][0]) # Sort the pins by a heuristic such as Min Spanning Tree or Rectilinear Steiner Tree netPinList = [] netPinCoord = [] for j in range(0, gridParameters['netInfo'][netNum]['numPins']): pin = tuple([ int((gridParameters['netInfo'][netNum][str(j + 1)][0] - gridParameters['Origin'][0]) / gridParameters['tileWidth']), int((gridParameters['netInfo'][netNum][str(j + 1)][1] - gridParameters['Origin'][1]) / gridParameters['tileHeight']), int(gridParameters['netInfo'][netNum][str(j + 1)][2]), int(gridParameters['netInfo'][netNum][str(j + 1)][0]), int(gridParameters['netInfo'][netNum][str(j + 1)][1]) ]) if pin[0:3] in netPinCoord: continue else: netPinList.append(pin) netPinCoord.append(pin[0:3]) twoPinList = [] for i in range(len(netPinList) - 1): pinStart = netPinList[i] pinEnd = netPinList[i + 1] twoPinList.append([pinStart, pinEnd]) # Insert Tree method to decompose two pin problems here twoPinList = tree.generateMST(twoPinList) # Remove pin pairs that are in the same grid nullPairList = [] for i in range(len(twoPinList)): if twoPinList[i][0][:3] == twoPinList[i][1][:3]: nullPairList.append(twoPinList[i]) for i in range(len(nullPairList)): twoPinList.reomove(nullPairList[i]) i = 1 routeListSingleNet = [] for twoPinPair in twoPinList: pinStart = twoPinPair[0] pinEnd = twoPinPair[1] route, cost = twoPinASearch.AStarSearchRouter( pinStart, pinEnd, gridGraphSearch) routeListSingleNet.append(route) i += 1 mergedrouteListSingleNet = [] for list in routeListSingleNet: # if len(routeListSingleNet[0]) == 2: # mergedrouteListSingleNet.append(list[0]) # mergedrouteListSingleNet.append(list[1]) # else: for loc in list: if loc not in mergedrouteListSingleNet: mergedrouteListSingleNet.append(loc) routeListMerged.append(mergedrouteListSingleNet) routeListNotMerged.append(routeListSingleNet) # Update capacity and grid graph after routing one pin pair # # WARNING: there are some bugs in capacity update # # # print(route) # capacity = graph.updateCapacity(capacity, mergedrouteListSingleNet) # gridGraph = twoPinASearch.AStarSearchGraph(gridParameters, capacity) # print('\nRoute List Merged:',routeListMerged) twopinlist_nonet = [] for net in twopinListCombo: for pinpair in net: twopinlist_nonet.append(pinpair) # Get two pin numbers twoPinNum = 0 twoPinNumEachNet = [] for i in range(len(init.gridParameters(grid_info)['netInfo'])): netNum = int(sortedHalfWireLength[i][0]) # i twoPinNum = twoPinNum + ( init.gridParameters(grid_info)['netInfo'][netNum]['numPins'] - 1) twoPinNumEachNet.append( init.gridParameters(grid_info)['netInfo'][netNum]['numPins'] - 1) # print('twoPinNumEachNet debug1: ',twoPinNumEachNet) # print('twopinlist_nonet',twopinlist_nonet) # DRL Module from here graphcase.max_step = 50 #20 graphcase.twopin_combo = twopinlist_nonet graphcase.net_pair = twoPinNumEachNet # print('graphcase.twopin_combo',graphcase.twopin_combo) # Setting the session to allow growth, so it doesn't allocate all GPU memory. gpu_ops = tf.GPUOptions(allow_growth=True) config = tf.ConfigProto(gpu_options=gpu_ops) sess = tf.Session(config=config) # Setting this as the default tensorflow session. keras.backend.tensorflow_backend.set_session(sess) # You want to create an instance of the DQN_Agent class here, and then train / test it. model_path = '../model/' data_path = '../data/' environment_name = 'grid' if not os.path.exists(model_path): os.makedirs(model_path) if not os.path.exists(data_path): os.makedirs(data_path) agent = DQN_Implementation.DQN_Agent(environment_name, sess, graphcase) # Burn in with search # Get a list of (observation, action, reward, observation_next, is_terminal) # with Route List Merged (solution given with A*search plus tree) graphcaseBurnIn = graph.GridGraph(init.gridParameters(grid_info)) graphcaseBurnIn.max_step = 10000 observationCombo = [] actionCombo = [] rewardCombo = [] observation_nextCombo = [] is_terminalCombo = [] for enumerator in range(300): for i in range(gridParameters['numNet']): goal = routeListMerged[i][-1] graphcaseBurnIn.goal_state = (goal[3], goal[4], goal[2], goal[0], goal[1]) for j in range(len(routeListMerged[i]) - 1): position = routeListMerged[i][j] nextposition = routeListMerged[i][j + 1] graphcaseBurnIn.current_state = (position[3], position[4], position[2], position[0], position[1]) # print(graphcaseBurnIn.state2obsv()) observationCombo.append(graphcaseBurnIn.state2obsv()) action = graph.get_action(position, nextposition) # print('action',action) actionCombo.append(action) graphcaseBurnIn.step(action) rewardCombo.append(graphcaseBurnIn.instantreward) # graphcaseBurnIn.current_state = (nextposition[3],nextposition[4], # nextposition[2],nextposition[0],nextposition[1]) observation_nextCombo.append(graphcaseBurnIn.state2obsv()) is_terminalCombo.append(False) is_terminalCombo[-1] = True # if testing using training function, comment burn_in agent.replay = DQN_Implementation.Replay_Memory( ) #Remove memeory of previous training agent.burn_in_memory_search(observationCombo, actionCombo, rewardCombo, observation_nextCombo, is_terminalCombo) twoPinNum = 0 twoPinNumEachNet = [] for i in range(len(init.gridParameters(grid_info)['netInfo'])): twoPinNum = twoPinNum + ( init.gridParameters(grid_info)['netInfo'][i]['numPins'] - 1) twoPinNumEachNet.append( init.gridParameters(grid_info)['netInfo'][i]['numPins'] - 1) # print ("Two pin num: ",len(graphcase.twopin_combo)) twoPinNum = len(graphcase.twopin_combo) twoPinNumEachNet = graphcase.twopin_combo # Training DRL savepath = model_path #32by32simple_model_train" # model_file = "../32by32simple_model_train/model_24000.ckpt" # print ('twoPinNumEachNet debug2',twoPinNumEachNet) # graphcase.max_step = 50 #20 # graphcase.twopin_combo = twopinlist_nonet # graphcase.net_pair = twoPinNumEachNet # Reinitialze grid graph parameters before training on new benchmarks agent.gridParameters = gridParameters agent.gridgraph.max_step = 50 agent.goal_state = None agent.init_state = None agent.gridgraph.capacity = capacity agent.gridgraph.route = [] agent.gridgraph.twopin_combo = twopinlist_nonet agent.gridgraph.twopin_pt = 0 agent.gridgraph.twopin_rdn = None agent.gridgraph.reward = 0.0 agent.gridgraph.instantreward = 0.0 agent.gridgraph.best_reward = 0.0 agent.gridgraph.best_route = [] agent.gridgraph.route_combo = [] agent.gridgraph.net_pair = twoPinEachNetClear agent.gridgraph.instantrewardcombo = [] agent.gridgraph.net_ind = 0 agent.gridgraph.pair_ind = 0 agent.gridgraph.posTwoPinNum = 0 agent.gridgraph.passby = np.zeros_like(capacity) agent.previous_action = -1 episodes = agent.max_episodes solution_combo_filled,reward_plot_combo,reward_plot_combo_pure,solutionTwoPin,posTwoPinNum \ = agent.train(twoPinNum,twoPinEachNetClear,netSort,savepath,model_file=None) # pkl.dump(solution_combo_filled,fileObject) # fileObject.close() # Generate output file for DRL solver # print('posTwoPinNum',posTwoPinNum) # print('len(graphcase.twopin_combo)',len(graphcase.twopin_combo)) if posTwoPinNum >= len(graphcase.twopin_combo): #twoPinNum: # Plot reward and save reward data n = np.linspace(1, episodes, len(reward_plot_combo)) plt.figure() plt.plot(n, reward_plot_combo) plt.xlabel('episodes') plt.ylabel('reward') plt.savefig('test_benchmark_{dumpBench}.DRLRewardPlot.jpg'.format( dumpBench=globali + 1)) # plt.show() # plt.close() n = np.linspace(1, episodes, len(reward_plot_combo_pure)) plt.figure() plt.plot(n, reward_plot_combo_pure) plt.xlabel('episodes') plt.ylabel('reward') plt.savefig( 'test_benchmark_{dumpBench}.DRLRewardPlotPure.jpg'.format( dumpBench=globali + 1)) filenameplot = '%s.rewardData' % filename np.save(filenameplot, reward_plot_combo) # dump solution of DRL f = open( 'solutionsDRL/test_benchmark_{dumpBench}.gr.DRLsolution'. format(dumpBench=globali + 1), 'w+') # for i in range(1): twoPinSolutionPointer = 0 routeListMerged = solution_combo_filled for i in range(gridParameters['numNet']): singleNetRouteCache = [] indicator = i netNum = int(sortedHalfWireLength[i][0]) # i i = netNum value = '{netName} {netID} {cost}\n'.format( netName=gridParameters['netInfo'][indicator]['netName'], netID=gridParameters['netInfo'][indicator]['netID'], cost=0) #max(0,len(routeListMerged[indicator])-1)) f.write(value) for j in range(len(routeListMerged[indicator]) - 1): a = routeListMerged[indicator][j] b = routeListMerged[indicator][j + 1] if (a[3], a[4], a[2], b[3], b[4], b[2]) not in singleNetRouteCache: singleNetRouteCache.append( (a[3], a[4], a[2], b[3], b[4], b[2])) singleNetRouteCache.append( (b[3], b[4], b[2], a[3], a[4], a[2])) diff = [ abs(a[2] - b[2]), abs(a[3] - b[3]), abs(a[4] - b[4]) ] if diff[1] > 2 or diff[2] > 2: continue elif diff[1] == 2 or diff[2] == 2: # print('Alert') continue elif diff[0] == 0 and diff[1] == 0 and diff[2] == 0: continue elif diff[0] + diff[1] + diff[2] >= 2: continue else: value = '({},{},{})-({},{},{})\n'.format( int(a[0]), int(a[1]), a[2], int(b[0]), int(b[1]), b[2]) f.write(value) twoPinSolutionPointer = twoPinSolutionPointer + 1 f.write('!\n') f.close() # Plot of routing for multilple net (RL solution) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.set_zlim(-0.5, 2.5) # Visualize solution for twoPinRoute in solutionTwoPin: x = [] y = [] z = [] for i in range(len(twoPinRoute)): # print(routeList[i]) # diff = [abs(routeList[i][2]-routeList[i+1][2]), # abs(routeList[i][3]-routeList[i+1][3]), # abs(routeList[i][4]-routeList[i+1][4])] # if diff[1] > 2 or diff[2] > 2: # continue # elif diff[1] == 2 or diff[2] == 2: # # print('Alert') # continue # elif diff[0] == 0 and diff[1] == 0 and diff[2] == 0: # continue # elif diff[0] + diff[1] + diff[2] >= 2: # continue # else: x.append(twoPinRoute[i][3]) y.append(twoPinRoute[i][4]) z.append(twoPinRoute[i][2]) ax.plot(x, y, z) plt.xlim([0, gridParameters['gridSize'][0] - 1]) plt.ylim([0, gridParameters['gridSize'][1] - 1]) plt.savefig( 'DRLRoutingVisualize test_benchmark_{dumpBench}.png'.format( dumpBench=globali + 1)) # plt.show() # plt.close() else: print("DRL fails with existing max episodes! : (") except IndexError: print("Invalid Benchmarks! ") agent.sess.close() tf.reset_default_graph() # graphcase.posTwoPinNum = 0 return
def DRLagent_generator(filename): grid_info = init.read(filename) for item in init.gridParameters(grid_info).items(): print(item) gridParameters = init.gridParameters(grid_info) # # GridGraph graphcase = graph.GridGraph(init.gridParameters(grid_info)) capacity = graphcase.generate_capacity() gridX, gridY, gridZ = graphcase.generate_grid() # Real Router for Multiple Net # Note: pinCoord input as absolute length coordinates gridGraphSearch = twoPinASearch.AStarSearchGraph(gridParameters, capacity) # Sort net halfWireLength = init.VisualGraph( init.gridParameters(grid_info)).bounding_length() sortedHalfWireLength = sorted(halfWireLength.items(), key=operator.itemgetter(1), reverse=True) # Large2Small netSort = [] for i in range(gridParameters['numNet']): order = int(sortedHalfWireLength[i][0]) netSort.append(order) routeListMerged = [] routeListNotMerged = [] # Getting two pin list combo (For RL) twopinListCombo = [] for i in range(len(init.gridParameters(grid_info)['netInfo'])): netNum = i netPinList = [] netPinCoord = [] for j in range(0, gridParameters['netInfo'][netNum]['numPins']): pin = tuple([ int((gridParameters['netInfo'][netNum][str(j + 1)][0] - gridParameters['Origin'][0]) / gridParameters['tileWidth']), int((gridParameters['netInfo'][netNum][str(j + 1)][1] - gridParameters['Origin'][1]) / gridParameters['tileHeight']), int(gridParameters['netInfo'][netNum][str(j + 1)][2]), int(gridParameters['netInfo'][netNum][str(j + 1)][0]), int(gridParameters['netInfo'][netNum][str(j + 1)][1]) ]) if pin[0:3] in netPinCoord: continue else: netPinList.append(pin) netPinCoord.append(pin[0:3]) twoPinList = [] for i in range(len(netPinList) - 1): pinStart = netPinList[i] pinEnd = netPinList[i + 1] twoPinList.append([pinStart, pinEnd]) # print('Two pin list vanilla:',twoPinList,'\n') twoPinListVanilla = twoPinList # Insert Tree method to decompose two pin problems here twoPinList = tree.generateMST(twoPinList) # Remove pin pairs that are in the same grid nullPairList = [] for i in range(len(twoPinListVanilla)): if twoPinListVanilla[i][0][:3] == twoPinListVanilla[i][1][:3]: nullPairList.append(twoPinListVanilla[i]) for i in range(len(nullPairList)): twoPinListVanilla.reomove(nullPairList[i]) # Remove pin pairs that are in the same grid nullPairList = [] for i in range(len(twoPinList)): if twoPinList[i][0][:3] == twoPinList[i][1][:3]: nullPairList.append(twoPinList[i]) for i in range(len(nullPairList)): twoPinList.reomove(nullPairList[i]) # Key: use original sequence of two pin pairs # twopinListCombo.append(twoPinListVanilla) for i in range(len(init.gridParameters(grid_info)['netInfo'])): netNum = int(sortedHalfWireLength[i][0]) # i # Sort the pins by a heuristic such as Min Spanning Tree or Rectilinear Steiner Tree netPinList = [] netPinCoord = [] for j in range(0, gridParameters['netInfo'][netNum]['numPins']): pin = tuple([ int((gridParameters['netInfo'][netNum][str(j + 1)][0] - gridParameters['Origin'][0]) / gridParameters['tileWidth']), int((gridParameters['netInfo'][netNum][str(j + 1)][1] - gridParameters['Origin'][1]) / gridParameters['tileHeight']), int(gridParameters['netInfo'][netNum][str(j + 1)][2]), int(gridParameters['netInfo'][netNum][str(j + 1)][0]), int(gridParameters['netInfo'][netNum][str(j + 1)][1]) ]) if pin[0:3] in netPinCoord: continue else: netPinList.append(pin) netPinCoord.append(pin[0:3]) twoPinList = [] for i in range(len(netPinList) - 1): pinStart = netPinList[i] pinEnd = netPinList[i + 1] twoPinList.append([pinStart, pinEnd]) # Insert Tree method to decompose two pin problems here twoPinList = tree.generateMST(twoPinList) # Remove pin pairs that are in the same grid nullPairList = [] for i in range(len(twoPinList)): if twoPinList[i][0][:3] == twoPinList[i][1][:3]: nullPairList.append(twoPinList[i]) for i in range(len(nullPairList)): twoPinList.reomove(nullPairList[i]) # Key: Use MST sorted pin pair sequence under half wirelength sorted nets twopinListCombo.append(twoPinList) # for i in range(1): for i in range(len(init.gridParameters(grid_info)['netInfo'])): # Determine nets to wire based on sorted nets (stored in list sortedHalfWireLength) # print('Routing net No.',init.gridParameters(grid_info)['netInfo'][int(sortedHalfWireLength[i][0])]['netName']) # (above output is to get actual netName) netNum = int(sortedHalfWireLength[i][0]) # Sort the pins by a heuristic such as Min Spanning Tree or Rectilinear Steiner Tree netPinList = [] netPinCoord = [] for j in range(0, gridParameters['netInfo'][netNum]['numPins']): pin = tuple([ int((gridParameters['netInfo'][netNum][str(j + 1)][0] - gridParameters['Origin'][0]) / gridParameters['tileWidth']), int((gridParameters['netInfo'][netNum][str(j + 1)][1] - gridParameters['Origin'][1]) / gridParameters['tileHeight']), int(gridParameters['netInfo'][netNum][str(j + 1)][2]), int(gridParameters['netInfo'][netNum][str(j + 1)][0]), int(gridParameters['netInfo'][netNum][str(j + 1)][1]) ]) if pin[0:3] in netPinCoord: continue else: netPinList.append(pin) netPinCoord.append(pin[0:3]) twoPinList = [] for i in range(len(netPinList) - 1): pinStart = netPinList[i] pinEnd = netPinList[i + 1] twoPinList.append([pinStart, pinEnd]) # Insert Tree method to decompose two pin problems here twoPinList = tree.generateMST(twoPinList) # Remove pin pairs that are in the same grid nullPairList = [] for i in range(len(twoPinList)): if twoPinList[i][0][:3] == twoPinList[i][1][:3]: nullPairList.append(twoPinList[i]) for i in range(len(nullPairList)): twoPinList.reomove(nullPairList[i]) i = 1 routeListSingleNet = [] for twoPinPair in twoPinList: pinStart = twoPinPair[0] pinEnd = twoPinPair[1] route, cost = twoPinASearch.AStarSearchRouter( pinStart, pinEnd, gridGraphSearch) routeListSingleNet.append(route) i += 1 mergedrouteListSingleNet = [] for list in routeListSingleNet: # if len(routeListSingleNet[0]) == 2: # mergedrouteListSingleNet.append(list[0]) # mergedrouteListSingleNet.append(list[1]) # else: for loc in list: if loc not in mergedrouteListSingleNet: mergedrouteListSingleNet.append(loc) routeListMerged.append(mergedrouteListSingleNet) routeListNotMerged.append(routeListSingleNet) twopinlist_nonet = [] for net in twopinListCombo: for pinpair in net: twopinlist_nonet.append(pinpair) # Get two pin numbers twoPinNum = 0 twoPinNumEachNet = [] for i in range(len(init.gridParameters(grid_info)['netInfo'])): netNum = int(sortedHalfWireLength[i][0]) # i twoPinNum = twoPinNum + ( init.gridParameters(grid_info)['netInfo'][netNum]['numPins'] - 1) twoPinNumEachNet.append( init.gridParameters(grid_info)['netInfo'][netNum]['numPins'] - 1) graphcase.max_step = 50 #20 graphcase.twopin_combo = twopinlist_nonet graphcase.net_pair = twoPinNumEachNet # Setting the session to allow growth, so it doesn't allocate all GPU memory. gpu_ops = tf.GPUOptions(allow_growth=True) config = tf.ConfigProto(gpu_options=gpu_ops) sess = tf.Session(config=config) # Setting this as the default tensorflow session. keras.backend.tensorflow_backend.set_session(sess) # You want to create an instance of the DQN_Agent class here, and then train / test it. model_path = '../model/' data_path = '../data/' environment_name = 'grid' if not os.path.exists(model_path): os.makedirs(model_path) if not os.path.exists(data_path): os.makedirs(data_path) agent = DQN_Implementation.DQN_Agent(environment_name, sess, graphcase) episodes = agent.max_episodes return agent, episodes, model_path, data_path, environment_name
def replanning_heuristics(original_graph, virtual_graph, list_of_H, FILE_2): #print 'Here is the beguinning of my function' PolC = original_graph['PolC'] colors_0 = ['b', 'r', 'g', 'y'] R = len(list_of_H) print '\n' for r in range(R): print 'popped_edges of robot ', list_of_H[r].id, ': ', list_of_H[ r].popped_edges print '\n' for r in range(R): print 'LastMeeting robot ', list_of_H[r].id, ': ', list_of_H[ r].lastMeeting list_of_robs = [] for r in range(R): list_of_robs.append(list_of_H[r].id) id = min(list_of_robs) #id of the robot that is computing the replan speeds = [] search_speeds = [] colors = [] for r in range(R): speeds.append(list_of_H[r].specs[0]) search_speeds.append(list_of_H[r].specs[1]) colors.append(colors_0[list_of_H[r].id]) # Compute old_cost, list_cost = myLib.get_cost(original_graph, list_of_H, speeds, search_speeds) # Call function to define the sests E_v, E_uv and E_g set_uv, set_v, set_g, pts, pts_id, e_vT_f_all = define_subsets_new( list_of_H, virtual_graph) # ---------- ---------- ---------- ---------- ---------- print '\nHere is set_v (visited edges) in original inedexes:' print set_v print 'Here is set_uv (unvisited edges) in original inedexes:' print set_uv print 'Here is set_g (assigned edges) in original inedexes:' print set_g, '\n\n' # Map the unvisited nodes with new labels C = virtual_graph['Ccom'] #matrix with the length costs Cuv = np.matrix( C ) # Reduced cost matrix with only the unvisited edges (unvisited virtual nodes) C = virtual_graph['C_sp'] #matrix with the number of search points Cuv_sp = np.matrix( C ) # Reduced cost matrix with only the unvisited edges (unvisited virtual nodes) exclude_list = (np.array(set_v) - 1).tolist() + (np.array(set_g) - 1).tolist() Cuv = np.delete(Cuv, exclude_list, 0) # exclude lines Cuv = np.delete(Cuv, exclude_list, 1) # exclude columns Cuv = Cuv.tolist() Cuv_sp = np.delete(Cuv_sp, exclude_list, 0) # exclude lines Cuv_sp = np.delete(Cuv_sp, exclude_list, 1) # exclude columns Cuv_sp = Cuv_sp.tolist() C_edge = [] for e in range(len(PolC[0])): cost = PolC[0][e][4] cost = cost.tolist() cost = cost[0] cost = cost[0] C_edge.append(cost) # -------------------------------------------------------------- # Define the depot virtual nodes for the task assignment depots = [] for r in range(R): #exec ('depots.append(set_uv.index(H%d.currEdge))' % r) depots.append(set_uv.index(list_of_H[r].currEdge)) #THE DEPOT POINT MAY NOT BE IN e_uv #print '\nHere is depot virtual nodes (new indexes):' #print depots #print 'Here is depot virtual nodes (original indexes):' depots_ori = [] #original depot points?? for r in range(R): depots_ori.append(set_uv[depots[r]]) #print depots_ori, '\n' #-------------------------------------------------------------- print '\n ----- Task assignment function called -----' import time as tm heu_time = tm.time() sol, division = TAHEU.heuristic_loop(original_graph, speeds, search_speeds, Cuv, Cuv_sp, pts, pts_id, depots, FILE_2) heu_time = tm.time() - heu_time print '\n- - - - - - - - - - heu_tot_time: ', heu_time #PASS THE DEPOT POINTS # ---------- ---------- ---------- ---------- ---------- ---------- ---------- # Sort the lists for r in range(R): division[r] = list(set(division[r])) # Map the nodes back to the original indexation for r in range(R): for k in range(len(division[r])): division[r][k] = set_uv[division[r][k]] #""" # Exclude/Remove the used depot virtual nodes (they are edges that were already visited) for r1 in range(R): for r2 in range(R): if list_of_H[r1].currEdge in division[r2]: # Remove currEdge only if it is not on e_v, because the robot may only be passing through the edge without searching on it #print 'AAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAA\n' if list_of_H[r1].currEdge in e_vT_f_all: #if list_of_H[r1].currEdge in list_of_H[r2].T_f: division[r2].pop(division[r2].index( list_of_H[r1].currEdge)) #print 'BBBBBBBBBBBBBBBBBB\nBBBBBBBBBBBBBBBBBB\n' #print 'division[r2]:\n', division[r2] set_v.append(list_of_H[r1].currEdge) print 'Edge appended: ', list_of_H[r1].currEdge # Include the used depot virtual nodes in the visited set #for r in range(R): # set_v.append(list_of_H[r].currEdge) #""" PL = False if PL == True: print '\nAssigned edges for the robots:' for r in range(R): print 'Subset for robot ' + str( list_of_H[r].id) + ': ', division[r] print '\n' # ---------- ---------- ---------- ---------- ---------- ---------- ---------- # Call MST for every robot in the communication graph in order to make the graph connected print '\n ----- Applying MST to the disconnected subgraphs ------' subgraphs = [] for r in range(R): subgraphs.append([]) pylab.figure(id) pylab.subplot(2, R, R + (r + 1)) subgraphs[r] = MST.MSTconnect(original_graph, division[r], (list_of_H[r]).nextNode, colors[r], True) PL = False if PL: for r in range(R): print 'Subset of edges for robot ' + str( list_of_H[r].id) + ': (original indexes)\n', subgraphs[r] print 'Start node for robot ' + str(list_of_H[r].id) + ':', ( list_of_H[r]).nextNode, '\n' # ---------- ---------- ---------- ---------- ---------- CPP_time = tm.time() # Cal CPP for every graph generated by the MST based algorithm print '\n ----- Applying CPP to the connected subgraphs -----' Hole_path_list = [] for r in range(R): Hole_path_list.append([]) current_node = (list_of_H[r]).nextNode if len(subgraphs[r]) > 0: edges_listOfTuples = myLib.write_listOfTuples( original_graph, subgraphs[r]) Hole_path_list[r] = CPPlib.main_CPP(sorted(edges_listOfTuples), current_node) else: Hole_path_list[r] = [] PL = False if PL: print 'Route for robot ' + str( list_of_H[r].id), ': ', Hole_path_list[r], '\n' print '\n' # ---------- ---------- ---------- ---------- ---------- CPP_time = tm.time() - CPP_time # Create list T_a pts_0 = virtual_graph['nodes'] T_a0 = [Intlist()] for k in range(len(PolC[0]) - 1): IL = Intlist() T_a0.append(IL) for k in range(len(pts_0)): T_a0[k].data = list(list_of_H[0].T_a[0].data) + list( list_of_H[1].T_a[1].data) T_a0[k].data = list(T_a0[k].data) if k + 1 in set_uv: # if in unvisite list if k + 1 in division[0]: # if in the assigned to the other one T_a0[k].data.append(list_of_H[0].id) elif k + 1 in division[1]: T_a0[k].data.append(list_of_H[1].id) T_a0[k].data = list(set(T_a0[k].data)) # Create list T_f T_f0 = [] for r in range(R): T_f0 = T_f0 + list(list_of_H[r].T_f) T_f0 = T_f0 + set_v T_f0 = list(set(T_f0)) # Create the new list of histories new_Hists = [] for r in range(R): H = History() H.id = list_of_H[r].id H.e_v = set_v H.e_uv = division[r] for r2 in range(R): if r2 != r: H.e_g = H.e_g + division[ r2] # + set_g !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! H.T_a = T_a0 H.T_f = T_f0 H.lastMeeting = [] for r2 in range(R): H.lastMeeting.append(list_of_H[r2].id) H.Whole_path = Hole_path_list[r] new_Hists.append(H) new_cost, list_cost = myLib.get_cost(original_graph, new_Hists, speeds, search_speeds) for r in range(len(list_of_H)): print 'cost ', list_of_H[r].id, ': ', list_cost[r] #print 'max cost: ', new_cost #print 'Old cost: ', old_cost #print 'New cost: ', new_cost # Check if the new plan is better than the previous one change_plan = False if new_cost < old_cost: change_plan = True # Initialize the plot of the result of the TA algorithm for r in range(R): pylab.subplot(2, R, (r + 1)) pylab.axis('equal') pylab.axis(virtual_graph['w_s']) pylab.title('Task assig. robot %d' % list_of_H[r].id) for e in range(len(PolC[0])): [fr, to, cx, cy, cost] = myLib.getCoefs(e, PolC) p0 = [0.01 * k for k in range(101)] x = [] y = [] for p in p0: x.append(0) y.append(0) for k in range(6): # Compute refference position x[-1] = x[-1] + cx[6 - k - 1] * p**k y[-1] = y[-1] + cy[6 - k - 1] * p**k # Plot the the edge in the background for r in range(R): pylab.subplot(2, R, (r + 1)) #pylab.plot(x, y, 'k--', linewidth=1.0) pylab.plot(x, y, 'k-', linewidth=1.0) for r in range(R): if e + 1 in division[r]: pylab.subplot(2, R, (r + 1)) pylab.plot(x, y, colors[r], linewidth=3.0) str_2 = "\t" + str(heu_time) for r in range(len(list_cost)): str_2 = str_2 + "\t" + str(list_cost[r]) str_2 = str_2 + "\t" + str(CPP_time) FILE_2.write(str_2) # If the new plan is not better compute a simple replan if not change_plan: # If the new plan from TA->MST->CPP is not better ok. However, we need to run CPP again because we have print 'New cost is not better ...' print '---------- ---------- ---------- ---------- ---------- ---------- ---------- ----------' print '---------- ---------- ---------- APPLYING THE SIMPLE REPLAN ---------- ---------- ----------' print '---------- ---------- ---------- ---------- ---------- ---------- ---------- ----------' division = [] for r in range(R): division.append([]) for r in range(R): for k in list_of_H[r].e_uv: if k in set_uv: division[r].append(k) print 'Here is new division (for the simple replan)' print division # Call MST for every robot in the communication graph in order to make the graph connected pylab.close() pylab.axis(virtual_graph['w_s']) print '\n ----- Applying MST to the disconnected subgraphs ------' subgraphs = [] for r in range(R): subgraphs.append([]) pylab.subplot(2, R, R + (r + 1)) subgraphs[r] = MST.MSTconnect(original_graph, division[r], (list_of_H[r]).nextNode, colors[r], True) for r in range(R): print 'Subset of edges for robot ' + str( list_of_H[r].id) + ': (original indexes)\n', subgraphs[r] print 'Start node for robot ' + str(list_of_H[r].id) + ':', ( list_of_H[r]).nextNode, '\n' # ---------- ---------- ---------- ---------- ---------- # Cal CPP for every graph generated by the MST based algorithm print '\n ----- Applying CPP to the connected subgraphs -----' Hole_path_list = [] for r in range(R): Hole_path_list.append([]) current_node = (list_of_H[r]).nextNode if len(subgraphs[r]) > 0: edges_listOfTuples = myLib.write_listOfTuples( original_graph, subgraphs[r]) Hole_path_list[r] = CPPlib.main_CPP(sorted(edges_listOfTuples), current_node) else: Hole_path_list[r] = [] print 'Route for robot ' + str( list_of_H[r].id), ': ', Hole_path_list[r], '\n' print '\n' # ---------- ---------- ---------- ---------- ---------- # Create the new list of histories (STILL MUST ADAPT TO A GENERAL NUMBER OF ROBOS) new_Hists = [] for r in range(R): H = History() H.id = list_of_H[r].id H.e_v = set_v H.e_uv = division[r] for r2 in range(R): if r2 != r: H.e_g = division[r2] + set_g H.T_a = T_a0 H.T_f = T_f0 H.lastMeeting = [] for r2 in range(R): H.lastMeeting.append(list_of_H[r2].id) H.Whole_path = Hole_path_list[r] new_Hists.append(H) # ---------- ---------- ---------- ---------- ---------- """ Nothing is being done with this yet """ # Set the abort_curr_edge flag in te case to robots are in the same edge for r1 in range(R): for r2 in range(r1 + 1, R, 1): # This way r1<r2 if (list_of_H[r1].currEdge == list_of_H[r2].currEdge): new_Hists[r2].abort_curr_edge = True # """ for r1 in range(R): for r2 in range(R): if (new_Hists[r1].currEdge in new_Hists[r2].e_v[0:-1]): new_Hists[r1].abort_curr_edge = True # """ # ---------- ---------- ---------- ---------- ---------- ---------- ---------- """ THE PROBLEM WITH THIS IS THAT THE MINIMUM ID ROBOT WILL KEEP SERACHING THE SPs THAT WERE ALREADY SEARCHED BY THE MAX ID ROBOT """ # Set the available flag as False for r in range(R): new_Hists[r].available = False # Save the result of TA and MST in a image import time hour = time.strftime("%Hh%Mm%Ss") date = time.strftime("d%dm%my%Y") rp = rospkg.RosPack() fig_name = rp.get_path('distributed') fig_name = fig_name + '/imagesResults/Results_' + date + '_' + hour + '.png' pylab.savefig(fig_name) # ---------- ---------- ---------- ---------- ---------- # Choose if the result of the planning will be platted or not #SHOW_NEW_PLAN = True SHOW_NEW_PLAN = False if SHOW_NEW_PLAN: pylab.show() pylab.close() return change_plan, Hole_path_list, new_Hists
# pinEnd = tuple([int((gridParameters['netInfo'][netNum][str(j+1)][0]-gridParameters['Origin'][0])/gridParameters['tileWidth']), # int((gridParameters['netInfo'][netNum][str(j+1)][1]-gridParameters['Origin'][1])/gridParameters['tileHeight']), # int(gridParameters['netInfo'][netNum][str(j+1)][2]), # int(gridParameters['netInfo'][netNum][str(j+1)][0]), # int(gridParameters['netInfo'][netNum][str(j+1)][1])]) # # # Remove pin pairs that are in the same grid # if pinStart[:3] == pinEnd[:3]: # continue # else: # twoPinList.append([pinStart,pinEnd]) # print('Two pin list:',twoPinList,'\n') # Insert Tree method to decompose two pin problems here twoPinList = tree.generateMST(twoPinList) # print('Two pin list after:', twoPinList, '\n') # Remove pin pairs that are in the same grid again nullPairList = [] for i in range(len(twoPinList)): if twoPinList[i][0][:3] == twoPinList[i][1][:3]: nullPairList.append(twoPinList[i]) for i in range(len(nullPairList)): twoPinList.reomove(nullPairList[i]) i = 1 routeListSingleNet = [] for twoPinPair in twoPinList: pinStart = twoPinPair[0]
edgeAB.pairwiseScore3 = spectralPlotting.associateMassDeltasEps( candidateDeltas, massDeltaValue, .02) totalPairwiseScore += edgeAB.pairwiseScore totalPairwiseScore2 += edgeAB.pairwiseScore2 totalPairwiseScore3 += edgeAB.pairwiseScore3 candidateEdgeList.append(edgeAB) candidateNetwork.pairwiseScore = totalPairwiseScore candidateNetwork.pairwiseScore2 = totalPairwiseScore2 candidateNetwork.pairwiseScore3 = totalPairwiseScore3 candidateNetwork.candidateEdges = candidateEdgeList #Using the set of edges in the candidate network, construct an Maximum Spanning Tree using pairwiseScore as the edge weight. maximalSpanningTree = MST.spanningTree(candidateEdgeList, lambda x: x.pairwiseScore, maximal=True) mstScore = 0 for edge in maximalSpanningTree: mstScore += edge.pairwiseScore candidateNetwork.mstScore = mstScore candidateNetwork.mstEdges = maximalSpanningTree #Double check results before sending to bahar :D totalEdgesSG = 0 for nodeID in group: totalEdgesSG += len(SG.nodes[nodeID].neighbors) for candidateNetwork in allSequences[1]: candidateSet = set([])
def keep_moving(H, time, time_start, T, pathNode, Hole_path, cx, cy, p, signal, new_task, new_path, original_graph, freq, pose, laserVec, d, Vd, Kp, id, edge, pub_stage): C = original_graph['C'] PathM = original_graph['PathM'] PolC = original_graph['PolC'] EdgeMap = original_graph['EdgeMap'] VX = 0 WZ = 0 end_flag = False change_edge = False #Indicated a change on edge - useful to force robots to finish a edge before accept a replan if time - time_start > T + 1 / freq: change_edge = True time_start = time if len(pathNode) > 1: new_path = 1 #robot ended a direct path only else: new_task = 1 #robot ended a complete path as well if new_task == 1: if len(Hole_path) > 1: i = Hole_path.pop(0) j = Hole_path[0] pathNode = getNodePath(i - 1, j - 1, PathM) new_task = 0 new_path = 1 else: print '\nNodes search completed\n' new_path = 1 #In theory,len(Hole_path) <= 1 implies len(e_uv) = 0 !!!!!!!!!!!!!!!!!!!!!! if new_path == 1: #if ((len(H['e_uv']) == 0 and not pop_all_edges_flag)): if ((len(H['e_uv']) == 0 and not H['popped_edges'])): #if ((len(H['e_uv']) == 0 and not H['popped_edges'])): #Acho que deve ser isso #pop_all_edges_flag = True H['popped_edges'] = True #H['available'] = False # H['popped_edges'] = True print '\n\n---------- ---------- ----------\nPOPPING ALL EDGES\n---------- ---------- ----------\n' for kk in range(len(PolC[0])): print kk + 1, '/', len(PolC[0]) if not (kk + 1 in H['e_v']) and not (kk + 1 in H['T_f']): H['e_uv'].append(kk + 1) print kk + 1, '/', len(PolC[0]), ' included' else: print kk + 1, '/', len(PolC[0]) if (len(H['e_uv']) == 0): print '\n---------- All the edges were already visited ----------\n' end_flag = True VX, WZ = 0, 0 #return H, time, time_start, T, pathNode, Hole_path, cx, cy, p, signal, new_task, new_path, VX, WZ, end_flag, edge, change_edge, pop_all_edges_flag return H, time, time_start, T, pathNode, Hole_path, cx, cy, p, signal, new_task, new_path, VX, WZ, end_flag, edge, change_edge H['e_g'] = [] print "Here is H['e_uv']" print H['e_uv'] print 'Here is pose', pose curr_node, lixo = get_current_node(original_graph, pose) curr_node = curr_node + 1 print 'Here is curr_node', curr_node vel = Twist() pub_stage.publish(vel) connected_subgraph = MST.MSTconnect(original_graph, H['e_uv'], curr_node, 'k', False) edges_listOfTuples = write_listOfTuples(original_graph, connected_subgraph) Hole_path = CPPlib.main_CPP(sorted(edges_listOfTuples), curr_node) print 'Here is Hole path' print Hole_path pathNode = [Hole_path[0], Hole_path[1]] i = Hole_path.pop(0) j = Hole_path[0] pathNode = getNodePath(i - 1, j - 1, PathM) new_task = 0 new_path = 1 #elif (len(H['e_uv']) == 0 and pop_all_edges_flag): #elif (len(H['e_uv']) == 0 and H['popped_edges']): elif (len(H['T_f']) == len(PolC[0])): print '\n---------- All popped edges were visited ----------\n' end_flag = True #return H, time, time_start, T, pathNode, Hole_path, cx, cy, p, signal, new_task, new_path, VX, WZ, end_flag, edge, change_edge, pop_all_edges_flag return H, time, time_start, T, pathNode, Hole_path, cx, cy, p, signal, new_task, new_path, VX, WZ, end_flag, edge, change_edge i = pathNode.pop(0) j = pathNode[0] T = C[i - 1][ j - 1] / Vd #This is valid because i and j are always direct neighbors [edge, signal] = getEdge(i, j, PolC) [fr, to, cx, cy, cost] = getCoefs(edge, PolC) if signal == 1: p = 0 #start the edge (polynomial) at the beginning and move to the end elif signal == -1: p = 1 #start the edge (polynomial) at the end and move to the beginning new_path = 0 # Update the History edge = EdgeMap[i - 1][j - 1] # Remove the edge from the list of unvisited nodes if edge in H['e_uv']: #print "\nXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX - "+str(edge)+"\n" H['e_uv'].pop(H['e_uv'].index(edge)) # Add the edge to the list of visited edges if not edge in H['e_v']: H['e_v'].append(edge) #Write in file that the edge was searched for posterior analysis rp = rospkg.RosPack() path = rp.get_path('distributed') path = path + '/text/visited_' + str(id) + '.txt' FILE = open(path, 'a') FILE.write(str(edge) + '\n') FILE.close() if not edge in H['T_f']: H['T_f'].append(edge) #Print information on screen print '\nRobot ' + str(id) print 'e_v:\n', H['e_v'] print 'e_uv:\n', H['e_uv'] print 'e_g:\n', H['e_g'] print 'T_f:\n', H['T_f'] print 'Whole_path:\n', Hole_path else: # Compute the velocity according to the polynomial edge [ux, uy, p] = compute_velocity(cx, cy, p, 1.0 / freq, signal, pose, Vd, Kp) # Apply th repulsive potential to avoid collision [ux, uy] = repulsive_potential(laserVec, pose, ux, uy) # Apply feedback linearization [VX, WZ] = feedback_linearization(ux, uy, pose, d) #return H, time, time_start, T, pathNode, Hole_path, cx, cy, p, signal, new_task, new_path, VX, WZ, end_flag, edge, change_edge, pop_all_edges_flag return H, time, time_start, T, pathNode, Hole_path, cx, cy, p, signal, new_task, new_path, VX, WZ, end_flag, edge, change_edge