def __add_relays(self, distance_multiplier): for i in self.__segment_list: if not i.has_hidden: mVal = i.point_a.angle_to(i.point_b) [x, y] = i.point_a.position.as_array relay_count = int(np.floor(i.distance / distance_multiplier)) for _ in range(relay_count): x, y = self.__move_along_line(mVal, distance_multiplier, x, y) self.relay_list.append(Node(Pos(x, y))) i.has_relays = True for i in self.__segment_list: if i.has_hidden: internal_found = np.inf for k in self.relay_list: query_distance = i.point_a.distance_to(k) if query_distance < internal_found: internal_found = query_distance [x, y] = k.position.as_array mVal = np.subtract(i.point_b.position.as_array, [x, y]) mVal = np.arctan2(mVal[1], mVal[0]) relay_count = int(np.floor(i.distance / distance_multiplier)) for j in range(relay_count): x, y = self.__move_along_line(mVal, distance_multiplier, x, y) self.relay_list.append(Node(Pos(x, y)))
def load_spot_graph(file): """ Load the graph structure from 'spot_graph' :param file: spot_graph :return: """ nodeset = {} lines = [line.rstrip("\n") for line in open(file, "r")] # initialize all the nodes for line in lines: tabs = line.split(" ") id = int(tabs[0]) node = Node(id, "D") parking_spots = set() if len(tabs) > 2: p_s = tabs[2].split(",") parking_spots = set(map(int, p_s)) node.parking_spots = parking_spots nodeset[id] = node # set neighbors for all the nodes for line in lines: tabs = line.split(" ") n_i = tabs[1].split(",") neighbors_id = set(map(int, n_i)) neighbors = [] for n in neighbors_id: neighbors.append(nodeset[n]) id = int(tabs[0]) nodeset[id].neighbors = set(neighbors) return nodeset
def split(self, node, s_f, s_v, next_active_nodes): ''' :param node: node to be splitted :param i_f: the index of feature to determine this split :param s_v: split value :param next_active_nodes: append two nodes after split :return: ''' indexes = node.get_index() values = self.X[indexes, s_f] left_indexes = indexes[np.where(values <= s_v)] right_indexes = indexes[np.where(values > s_v)] left_node = Node(left_indexes) right_node = Node(right_indexes) node.set_kids(left_node, right_node) del_index = self.leafs.index(node) del self.leafs[del_index] self.leafs.insert(del_index, left_node) self.leafs.insert(del_index + 1, right_node) self.nodes.append(left_node) self.nodes.append(right_node) next_active_nodes.append(left_node) next_active_nodes.append(right_node)
def empty_row(i, square_width, total_col): cur_row = [] for c in range(total_col): if c % (square_width + 1) == 0: cur_row.append(Node(i * total_col + c, "C")) else: cur_row.append(Node(i * total_col + c, "D")) return cur_row
def mid_row(i, square_width, total_col): cur_row = [] for c in range(total_col): if c % (square_width + 1) == 0: cur_row.append(Node(i * total_col + c, "D")) elif c % (square_width + 1) == 1 or c % (square_width + 1) == square_width: cur_row.append(Node(i * total_col + c, "P")) else: cur_row.append(Node(i * total_col + c, "N")) return cur_row
def get_mini_graph(row, column, row_spots, column_spots): start = Node(0, "C") square_width = 2 + row_spots square_height = 2 + column_spots for i in range(row): container = set() for j in range(column): index = i * column + j if j % square_width == 0: container = set() else: container.add(Node(index, "m"))
def follow(self): try: self.proof.node_list = self.environment self.proof.execute_pipeline() except: pass # for x in self.environment_relays: # if self.type is NodeType.Relay: # self.move_along_line(self.angle_to(x), (self.distance_to(x) - self.unit_distance) * .2) # try: # self.move_along_line(self.angle_to(self.proof.relay_list[0]), # self.distance_to(self.proof.relay_list[0]) * .2) # except: # pass for x in self.pursue_target: print("we runnning") if self.type is NodeType.Relay: self.move_along_line( self.angle_to(x), (self.distance_to(x) - self.unit_distance) * .2) try: self.move_along_line( self.angle_to(self.proof.relay_list[0]), self.distance_to(self.proof.relay_list[0]) * .6) print("it gets triggered") except: pass elif self.type is NodeType.Home: if self.distance_to(x) > self.unit_distance * .8: new_node = MultiForwardPursueNode( [self.__a, self.__global_relay_link], self.unit_distance, in_node=Node(Pos(0, 0))) new_node.type = NodeType.Relay new_node.move_along_line(new_node.angle_to(x), self.distance_to(x) * .8) new_node.pursue_target.append(x) self.pursue_target.append(new_node) self.pursue_target.remove(x) self.__global_relay_link.append(new_node) # if in call-back range if self.distance_to(x) < self.unit_distance * .1: current_target = x little_set = self.pursue_target + current_target.pursue_target self.pursue_target = set(little_set) try: self.__global_relay_link.remove(current_target) print("triggered from the bottom") except: print("form the bottom") self.proof.reset()
def update_best_node(knowledge, all_pair, prev_path, nodeset, cur_node, exit_node, d_cost, w_cost, u_cost): """ Recompute the best node and cost after every movement :param knowledge: :param prev_path: :param nodeset: :param cur_node: :param exit_node: :param d_cost: :param w_cost: :return: """ best_cost = 250 # dummy best node best_node = Node(-1) for i in range(len(knowledge)): if knowledge[i] > 0: walk_cost = len(shortest_path(all_pair, nodeset[i], exit_node)) * w_cost drive_path = shortest_path(all_pair, cur_node, nodeset[i]) drive_cost = len(drive_path) * d_cost uturn_cost = u_cost if is_uturn(prev_path, drive_path) else 0 cost = drive_cost + walk_cost + uturn_cost if cost < best_cost: best_cost = cost best_node = nodeset[i] return best_cost, best_node
def refresh(self): self.nodes = [] self.leafs = [] self.root = Node(np.array(range(len(self.Y)))) self.nodes.append(self.root) self.leafs.append(self.root) self.finish_splitting = False
def move_to(self): [xs, ys] = self.move_centroid() tmp = Node(Pos(xs, ys)) self.move_along_line(self.angle_to(tmp), min([self.distance_to(tmp), self.max_velocity])) if COMPRESSION_DECOMPRESSION_FIX: try: [xs, ys] = self.child_centroid() tmp = Node(Pos(xs, ys)) self.move_along_line( self.angle_to(tmp), min([ self.distance_to(tmp) - self.critical_range, self.max_velocity ])) except: pass
def follow(self): if self.type is NodeType.Relay: # a propegated velocity is used to move everything around self.proof.node_list = self.environment self.move_along_line(self.angle_to(self.pursue_target), (self.distance_to(self.pursue_target) - self.unit_distance)) try: if len(self.environment) is 2: if self.environment[0].distance_to(self.environment[1]) > 0.8 * self.unit_distance: [xs, ys] = self.environment_centroid to_go = Node(Pos(xs, ys)) self.move_along_line(self.angle_to(to_go), self.distance_to(to_go)) except Exception as e: print(e) pass self.proof.reset() elif self.type is NodeType.Home: if self.distance_to(self.pursue_target) > self.unit_distance * .8: new_node = SmartNode([self.__a, self.__global_relay_link], self.unit_distance, in_node=Node(Pos(0, 0))) new_node.type = NodeType.Relay new_node.move_along_line(new_node.angle_to(self.pursue_target), self.distance_to(self.pursue_target) * .8) new_node.pursue_target = self.pursue_target self.pursue_target = new_node self.__global_relay_link.append(new_node) # if in call-back range if self.distance_to(self.pursue_target) < self.unit_distance * .1: current_target = self.pursue_target self.pursue_target = current_target.pursue_target try: self.__global_relay_link.remove(current_target) except Exception as e: print(e) print("Node removal error")
def spawn_to(self, target): new_node = BackwardPursueNode([self.__a, self.__global_relay_link], self.unit_distance, in_node=Node(Pos(0, 0))) new_node.type = NodeType.Relay new_node.move_to(target) new_node.follower = self new_node.depth = self.depth_counter target.follower = new_node self.__global_relay_link.append(new_node)
def split(self, node, s_f, s_v): ''' :param node: node to be splitted :param i_f: the index of feature to determine this split :param s_v: :return: ''' indexes = node.get_index() values = self.X[indexes,s_f] left_indexes = indexes[np.where(values <= s_v)] right_indexes = indexes[np.where(values > s_v)] left_node = Node(left_indexes) right_node = Node(right_indexes) node.set_kids(left_node, right_node) self.leafs.remove(node) self.leafs.append(left_node) self.leafs.append(right_node) self.nodes.append(left_node) self.nodes.append(right_node)
def execute(spot_map, nodeset, all_pair, knowledge, enter_node, exit_node, x, d_cost, w_cost, u_cost, default_best_cost, saving_threshold): cur_node = enter_node best_cost = default_best_cost # dummy best node best_node = Node(0, "D") prev_path = [enter_node] finished = False gain_knowledge(knowledge, cur_node, spot_map) back_steps = 0 while not finished: # possible candidates of each direction choices = search_by_depth(all_pair, cur_node, best_cost, d_cost, nodeset) # saving time expectation of each direction exp = choice_expectation(knowledge, spot_map, all_pair, choices, exit_node, prev_path, best_cost, d_cost, w_cost, u_cost, x) # best expected saving time next_node, best_saving = max(exp.items(), key=lambda t_e: t_e[1]) if best_saving <= saving_threshold: if cur_node == best_node: # arrive at best spot finished = True else: # head to current best spot path = shortest_path(all_pair, cur_node, best_node) if len(path) == 1 or len(path) == 0: print(saving_threshold, x, cur_node.id, best_node.id, exp) cur_node = path[1] back_steps += 1 else: cur_node = next_node gain_knowledge(knowledge, cur_node, spot_map) prev_path.append(cur_node) best_cost, best_node = update_best_node(knowledge, all_pair, prev_path, nodeset, cur_node, exit_node, best_cost, best_node, d_cost, w_cost, u_cost) if all_node_visited(nodeset, knowledge): finished = True if len(prev_path) > 8000: print(str(prev_path[-1]), str(prev_path[-2]), str(prev_path[-3])) raise Exception("Fall into infinite loop") return best_node, prev_path, back_steps
def execute_pipeline(self): for i in self.node_list[1:]: count = int( np.floor(self.node_list[0].distance_to(i) / self.unit_distance)) [x, y] = self.node_list[0].position.as_array for _ in range(count): x, y = self.__move_along_line(self.node_list[0].angle_to(i), self.unit_distance, x, y) self.relay_list.append(Node(Pos(x, y)))
def send_frame_process(self, frame: Frame, receiver: Node, port_in: int, sending_time: float, sender: Node, inspector: SendingProcessInspector = None): """ :param frame: frame that is being send :param receiver: receiving node :param port_in: receiving node ingress port :param sending_time: time it takes to send this frame :param sender: sending node :param inspector: inspector """ start_time = self.now if inspector is not None: inspector.finish_time = self.now + sending_time sending = True while sending_time > 0: try: if sending: yield self.timeout(sending_time) sending_time = 0 receiver.push(frame, port_in) frame.on_hop(sender, receiver) if receiver.address == frame.destination: frame.on_destination_reached(receiver) else: yield self.sleep_event except simpy.Interrupt: if sending: sending_time -= self.now - start_time inspector.finish_time = -1 else: start_time = self.now # some bytes need to be transmitted to signal that the frame is continued sending_time += inspector.get_penalty_time() inspector.finish_time = self.now + sending_time sending = not sending
def follow(self): if self.type is NodeType.Relay: # a propegated velocity is used to move everything around print("follow works") self.proof.node_list = self.environment self.move_along_line( self.angle_to(self.pursue_target), (self.distance_to(self.pursue_target) - self.unit_distance) * .2) try: self.proof.execute_pipeline() self.move_along_line( self.angle_to(self.proof.relay_list[0]), self.distance_to(self.proof.relay_list[0]) * .2) self.proof.reset() except: pass elif self.type is NodeType.Home: if self.distance_to(self.pursue_target) > self.unit_distance * .8: new_node = ForwardPursueNode( [self.__a, self.__global_relay_link], self.unit_distance, in_node=Node(Pos(0, 0))) new_node.type = NodeType.Relay new_node.move_along_line( new_node.angle_to(self.pursue_target), self.distance_to(self.pursue_target) * .8) new_node.pursue_target = self.pursue_target self.pursue_target = new_node self.__global_relay_link.append(new_node) # if in call-back range if self.distance_to(self.pursue_target) < self.unit_distance * .1: current_target = self.pursue_target self.pursue_target = current_target.pursue_target try: self.__global_relay_link.remove(current_target) except Exception as e: print(e) print("Node removal error")
def spawn_to(self, target): new_node = DecentralizedNode([self.__a, self.__global_relay_link], self.unit_distance, in_node=Node(Pos(0, 0))) new_node.type = NodeType.Relay new_node.parent = self new_node.children.append(target) self.children.remove(target) self.children.append(new_node) target.parent = new_node new_node.move_to() self.__global_relay_link.append(new_node)
def execute_pipeline(self): execution_list = self.node_list[1:] resource_list = [self.node_list[0]] for i in execution_list: min_acc = 1000000000 min_pair = [0, 1] for j in resource_list: if i.distance_to(j) < min_acc: min_acc = i.distance_to(j) min_pair = [i, j] [i, j] = min_pair count = int(np.floor(i.distance_to(j) / self.unit_distance)) [x, y] = i.position.as_array for _ in range(count): x, y = self.__move_along_line(i.angle_to(j), self.unit_distance, x, y) resource_list.append(Node(Pos(x, y))) self.relay_list = resource_list[1:]
def follow(self): for x in self.pursue_target: if self.distance_to(x) > self.unit_distance * .8: if self.type is NodeType.Relay: self.move_along_line( self.angle_to(x), (self.distance_to(x) - self.unit_distance) * .2) try: self.proof.execute_pipeline() self.move_along_line( self.angle_to(self.proof.relay_list[0]), self.distance_to(self.proof.relay_list[0]) * .6) self.proof.reset() except: pass elif self.type is NodeType.Home: for r in self.__global_relay_link[1:]: if x.distance_to(r) < self.unit_distance * .7: r.pursue_target.append(x) self.pursue_target.remove(x) if r not in self.pursue_target: self.pursue_target.append(r) break if x in self.pursue_target: new_node = MultiForwardPursueNode( [self.__a, self.__global_relay_link], self.unit_distance, in_node=Node(Pos(0, 0))) new_node.type = NodeType.Relay new_node.move_along_line(new_node.angle_to(x), self.distance_to(x) * .8) new_node.pursue_target.append(x) # needs work self.pursue_target.remove(x) self.pursue_target.append(new_node) self.__global_relay_link.append(new_node)
def uturn_exp(drive_path, cur_slot, exit_slot, slot_map, d_cost, w_cost, u_cost, default_cost=90): min_node, min_cost = Node(-1), 1000000000 for slot in drive_path: if len(slot.empty_parking_slot(slot_map)) > 0: path = min(search_by_end(cur_slot, slot, set()), key=lambda p: len(p)) cost = len(path) * d_cost + walk(cur_slot, exit_slot, w_cost) + u_cost if cost < min_cost: min_node = slot min_cost = cost if min_node.id == -1: return default_cost return min_cost
def execute(spot_map, nodeset, all_pair, knowledge, enter_node, exit_node, p_available, d_cost, w_cost, default_best_cost): cur_node = enter_node best_cost = default_best_cost best_node = Node(-1) prev_path = [enter_node] finished = False gain_knowledge(knowledge, cur_node, spot_map) while not finished: # print(cur_node) if cur_node.id == 218: print() choices = search_by_depth(all_pair, cur_node, best_cost, d_cost, nodeset) exp = choice_expectation(knowledge, all_pair, choices, exit_node, prev_path, best_cost, d_cost, w_cost, u_cost, p_available) next_node, best_exp = min(exp.items(), key=lambda e: e[1]) if best_exp > best_cost: finished = True else: cur_node = next_node gain_knowledge(knowledge, cur_node, spot_map) prev_path.append(cur_node) best_cost, best_node = update_best_node(knowledge, all_pair, prev_path, nodeset, cur_node, exit_node, d_cost, w_cost, u_cost) if all_node_visited(nodeset, knowledge): finished = True if len(prev_path) > 200: print(str(prev_path[-1]), str(prev_path[-2])) raise Exception("Fall into infinite loop") return best_node, prev_path
def move_to(self, target): self.call_counter = 0 self.last_caller = target if self.type == NodeType.Relay: # chain tightening code self.move_along_line(self.angle_to(target), (self.distance_to(target) - self.unit_distance) * .2) try: if len(self.environment) is 2: if self.environment[0].distance_to(self.environment[1]) > 0.8 * self.unit_distance: [xs, ys] = self.environment_centroid to_go = Node(Pos(xs, ys)) self.move_along_line(self.angle_to(to_go), self.distance_to(to_go) * 0.6) except IndexError as e: log.error("--------------------------------------------------") log.error("try failed - couldn't find a solution") log.error(e) # # force it for now if self.home not in self.environment_full: try: for j in self.follower.environment_infrastructure: if self.last_caller is j: self.last_caller.follower = self self.__global_relay_link.remove(self) self.last_caller.follower = self self.__global_relay_link.remove(self) log.error("Problem solved") except Exception as er: log.error(er) log.error("no hope in this one") if self.type == NodeType.Home: if self.distance_to(target) > self.unit_distance * .8: self.spawn_to(target) if self.type == NodeType.End: # if self.distance_to(target) > self.unit_distance * .8: target.follower = self.follower
def __init__(self, X, Y, ls_split_features, ls_split_values, leaf_feature_ls, leaf_beta_ls): ''' :param X: data, numpy array :param Y: labels, numpy array :param ls_split_featuress: the size of this list is the number of layers in the tree :param ls_split_values: value used to split :param leaf_feature_ls: features used for each leaf to fit a logistic regression :param leaf_beta_ls: betas used for each leaf to generate labels ''' self.X = X self.Y = Y self.ls_split_features = ls_split_features self.ls_split_values = ls_split_values self.leaf_feature_ls = leaf_feature_ls self.leaf_beta_ls = leaf_beta_ls self.nodes = [] self.leafs = [] self.root = Node(np.array(range(len(Y)))) self.nodes.append(self.root) self.leafs.append(self.root) self.finish_splitting = False
def move_to(self, target): self.call_counter = 0 self.last_caller = target if self.type == NodeType.Relay: # chain tightening code self.move_along_line( self.angle_to(target), (self.distance_to(target) - self.unit_distance) * .2) if len(self.environment) is 2: if self.environment[0].distance_to( self.environment[1]) > 0.8 * self.unit_distance: [xs, ys] = self.environment_centroid to_go = Node(Pos(xs, ys)) self.move_along_line(self.angle_to(to_go), self.distance_to(to_go) * 0.6) if self.type == NodeType.Home: if self.distance_to(target) > self.unit_distance * .8: self.spawn_to(target) if self.type == NodeType.End: # if self.distance_to(target) > self.unit_distance * .8: target.follower = self.follower
import time from pygame.constants import * from forward_distributed_solution.ForwardDecentralizedSolution import ForwardDecentralizedSolution, ForwardPursueNode from greedy_central_solution import GreedyCentralSolution from fui import WindowManager from simulation.node import Node, Pos if __name__ == "__main__": node_selector = 1 move_coefficient = 10 # create a list of nodes, this is our scenario node_list = [] a_node = Node(Pos(0, 0)) b_node = Node(Pos(1.7 * 10, 1 * 10)) c_node = Node(Pos(2 * 10, 2 * 10)) node_list.append(a_node) node_list.append(b_node) # node_list.append(c_node) # shove the list into a scenario solver dist_list = ForwardDecentralizedSolution(40, node_list) greedy_list = GreedyCentralSolution(40 * .8, node_list) game_window = WindowManager() while True:
for x in relays: tmp_count = 0 for y in relays: if x != y: if x.type != NodeType.End: if x.distance_to(y) <= unit_dis * 1: tmp_count += 1 if tmp_count > 2: multi_link_count += 1 return multi_link_count if __name__ == "__main__": nodes_list = [] random.seed(9001) a_node = Node(Pos(0, 0)) nodes_list.append(a_node) combined_simulator = [] combined_simulator.append( PursueCentralSmarterSolution(UNIT_DISTANCE, nodes_list)) combined_simulator.append(GreedyCentralSolution(UNIT_DISTANCE, nodes_list)) combined_simulator.append(DecentralizedSolution(UNIT_DISTANCE, nodes_list)) combined_simulator.append(PursueCentralSolution(UNIT_DISTANCE, nodes_list)) nodes_list.append( DecentralizedNode(combined_simulator[2].sandbox, UNIT_DISTANCE, in_node=Node(Pos(10, 10)))) combined_simulator[2].prepare() average_list = [np.zeros(len(combined_simulator))]
def add(self, new_node: Node = None): if new_node is None: self.node_list.append(Node(None, self.address_provider.get_address())) else: self.node_list.append(new_node)
np.savetxt('relay-list.csv', relay_pos, delimiter=',') np.savetxt('node-list.csv', node_pos, delimiter=',') def to_plot(self): node_pos, relay_pos = self.to_points() relay_pos = np.array(relay_pos) node_pos = np.array(node_pos) import matplotlib.pyplot as plt plt.scatter(node_pos[:, 0], node_pos[:, 1], c="r") plt.scatter(relay_pos[:, 0], relay_pos[:, 1], c="b") plt.axis('equal') plt.show() if __name__ == "__main__": test_list = NodeNetwork() test_list.add(Node(Pos(0, 0))) test_list.add(Node(Pos(10, 11))) test_list.add(Node(Pos(9, 20))) test_list.add(Node(Pos(25, 18))) test_list.add(Node(Pos(2, 15))) test_list.add(Node(Pos(18, -5))) test_list.add(Node(Pos(25, 25))) test_list.add(Node(Pos(-5, 25))) print(test_list.list)
from pygame.constants import * from forward_distributed_solution.MultiForwardDecentralizedSolution import MultiForwardDecentralizedSolution from greedy_central_solution import GreedyCentralSolution from fui import WindowManager from simulation.node import Node, Pos from simulation.node.Node import NodeType if __name__ == "__main__": node_selector = 1 move_coefficient = 10 # create a list of nodes, this is our scenario node_list = [] a_node = Node(Pos(0, 0)) b_node = Node(Pos(1.7 * 10, 1 * 10)) c_node = Node(Pos(2 * 10, 2 * 10)) node_list.append(a_node) node_list.append(b_node) # node_list.append(c_node) # shove the list into a scenario solver dist_list = MultiForwardDecentralizedSolution(40, node_list) greedy_list = GreedyCentralSolution(40 * .8, node_list) game_window = WindowManager() while True: