def __init__(self, number_of_nodes): sink = Node('Sink') sink.rank = self.RANK_INCREASE self.number_of_nodes = number_of_nodes self.nodes = [sink] self.slotframe = Slotframe()
def build_topology(self): sink = self.nodes[0] for node in range(self.number_of_nodes): new_node = Node("Node {}".format(node)) if len(self.nodes) == 1: new_node.rank = sink.rank + self.RANK_INCREASE new_node.parent = sink else: parent = self.nodes[randint(0, len(self.nodes) - 1)] new_node.parent = parent new_node.rank = parent.rank + self.RANK_INCREASE self.nodes.append(new_node) joining_node = Node("Joining node") joining_node.is_synchronized = False joining_node.active_frequency = randint(11, 26) self.nodes.append(joining_node)
# Set message printing level Simulator.EXTRA_VERBOSE = False Simulator.VERBOSE = False Channel.VERBOSE = False Node.EXTRA_VERBOSE = False Node.EXTRA_VERBOSE = False sim = Simulator() loss_rate = 0.60 # loss rate (0.0 to 1.0) min_delay = 0.000001 # 1 micro-second minimum delay mean_dealy = 0.000020 # 20 micro-second delay delay_generator = ExponentialDelay(min_delay, mean_dealy) alice_output = Channel(sim, delay_generator, loss_rate) alice = Node(sim, "ALICE", True, alice_output) bob_output = Channel(sim, delay_generator, loss_rate) bob = Node(sim, "BOB ", False, bob_output) alice.set_peer(bob) bob.set_peer(alice) sim.run_count(1000) alice.print_stats() bob.print_stats() print "trail {:6} Alice is {}, Bob is {}".format( trial + 1, "OK" if alice.data_ready else "NOT OK",
def run_trial(trial, alice_reboot_at=0.0, bob_reboot_at=0.0): sim = Simulator() delay_generator = ExponentialDelay(min_delay, mean_dealy) alice_output = Channel(sim, delay_generator, loss_rate) alice = Node(sim, "ALICE", alice_output) bob_output = Channel(sim, delay_generator, loss_rate) bob = Node(sim, "BOB ", bob_output) alice.set_peer(bob) bob.set_peer(alice) # Alice will reboot 10 seconds after she goes in to (OK, OK) mode. if alice_reboot_at > 0: alice.reboot_after(alice_reboot_at, 2.0) if bob_reboot_at > 0: bob.reboot_after(bob_reboot_at, 2.0) sim.run_count(2000) alice.print_stats() bob.print_stats() print "trail {:6} Alice is {}, Bob is {}".format( trial, "OK" if alice.data_ready else "NOT OK", "OK" if bob.data_ready else "NOT OK", ) sys.stdout.flush() print "" if not alice.data_ready or not bob.data_ready: raise RuntimeError("Terminated in failure mode")
def run(self, num_time_instances=100, num_nodes=100, num_anchors=25, stage_size=(500, 500), max_v=50, communication_radius=50): algorithm_results = { 'number_of_packets': {}, 'distance_error': {}, 'distance_error_all': {}, 'position_error': {}, 'prediction_time': {}, 'normalized_prediction_time': {}, 'number_of_samples': {}, } simulator_results = { 'node_positions': [], 'avg_number_of_first_hop_neighbors': [], 'avg_number_of_second_hop_neighbors': [], } config = { 'max_x': stage_size[0], 'max_y': stage_size[1], 'max_v': max_v, 'communication_radius': communication_radius, } # Initialize Results Dictionaries for algo in self.algorithms: for k in algorithm_results.keys(): algorithm_results[k][algo.name()] = [] for i in range(num_nodes): simulator_results['node_positions'].append([]) # Initialize Nodes for i in range(num_nodes): # type: int self.nodes.append(Node(i, i < num_anchors, config=config)) for t in range(num_time_instances): print("t:", t) # Move each node for n in self.nodes: # type: Node n.move() # Build state matrix and neighbor lists self.update_global_state_matrix(self.nodes, communication_radius) self.update_one_hop_neighbors_lists(self.nodes) self.update_two_hop_neighbors_lists(self.nodes) avg_number_of_first_hop_neighbors = sum( [len(n.one_hop_neighbors) for n in self.nodes]) / len(self.nodes) avg_number_of_second_hop_neighbors = sum( [len(n.two_hop_neighbors) for n in self.nodes]) / len(self.nodes) simulator_results['avg_number_of_first_hop_neighbors'].append( avg_number_of_first_hop_neighbors) simulator_results['avg_number_of_second_hop_neighbors'].append( avg_number_of_second_hop_neighbors) # Log node positions for i in range(len(self.nodes)): simulator_results['node_positions'][i].append( self.nodes[i].currentP) # Simulate Communication for algo in self.algorithms: # type: BaseMCL algo.communication(self.nodes, self.previous_global_state_matrix, self.current_global_state_matrix) algorithm_results['number_of_packets'][algo.name()].append( algo.get_total_number_of_packets()) # Make predictions for all nodes for algo in self.algorithms: start_time = time.time() for n in self.nodes: n.one_hop_neighbor_predicted_distances[algo.name()] = {} random.seed(t) algorithm_results['number_of_samples'][algo.name()].append( algo.predict(config, self.nodes, self.current_global_state_matrix)) end_time = time.time() algorithm_results['prediction_time'][algo.name()].append( end_time - start_time) avg_number_of_points_per_sample = 1 if not isinstance( algo, TrinaryMCL) else (avg_number_of_first_hop_neighbors + avg_number_of_second_hop_neighbors) algorithm_results['normalized_prediction_time'][ algo.name()].append((end_time - start_time) / avg_number_of_points_per_sample) # Evaluate Distance Error (Trinary) for algo in self.algorithms: total_distance_error = 0.0 distance_errors_all = [] count = 0 for i, n1 in enumerate(self.nodes): # type: Node # Anchors never add to the distance error if isinstance(algo, TrinaryMCL) or not n1.is_anchor: # for n2 in n1.one_hop_neighbors + n1.two_hop_neighbors: for j, n2 in enumerate(self.nodes): # type: Node if self.current_global_state_matrix[i, j] > 0: distance_predicted = n1.one_hop_neighbor_predicted_distances[ algo.name( )][n2] if n2 in n1.one_hop_neighbor_predicted_distances[ algo.name()] else 0.0 distance_actual = n1.distance(n2) if math.isnan(distance_predicted): distance_predicted = 0.0 total_distance_error += abs(distance_actual - distance_predicted) distance_errors_all.append( abs(distance_actual - distance_predicted)) count += 1 algorithm_results['distance_error'][algo.name()].append( total_distance_error / count if count > 0 else 0.0) algorithm_results['distance_error_all'][algo.name()].append( distance_errors_all) # Evaluate Position Error (non-Trinary) for algo in self.algorithms: if not isinstance(algo, TrinaryMCL): total_error = 0.0 for i, n1 in enumerate(self.nodes): # type: Node if not math.isnan(n1.p_pred[algo.name()].x): total_error += n1.currentP.distance( n1.p_pred[algo.name()]) algorithm_results['position_error'][algo.name()].append( total_error) return simulator_results, algorithm_results
def run(self, num_time_instances=2, num_nodes=4, num_anchors=25, stage_size=(200, 200), max_v=50, communication_radius=50, should_plot=True): config = { 'max_x': stage_size[0], 'max_y': stage_size[1], 'max_v': max_v, 'communication_radius': communication_radius, } self.algorithms = [ TrinaryMCL(), ] # Trinary Example self.nodes = [] NUM_NODES_TO_RENDER = num_nodes # random.seed(NUM_NODES_TO_RENDER) for i in range(NUM_NODES_TO_RENDER): if i > 0: MAX_MOVEMENT = 2.0 new_p = Point(random.random() * (config['communication_radius'] * MAX_MOVEMENT) - (config['communication_radius'] * MAX_MOVEMENT / 2), random.random() * (config['communication_radius'] * MAX_MOVEMENT) - (config['communication_radius'] * MAX_MOVEMENT / 2)) random_int = i - math.ceil((min(5,i)) * random.random()) new_p.x += self.nodes[random_int].currentP.x new_p.y += self.nodes[random_int].currentP.y self.nodes.append(Node(i, is_anchor=False, config=config, currentP=new_p)) else: self.nodes.append(Node(i, is_anchor=False, config=config, currentP=Point(0, 0))) # Build state matrix and neighbor lists # Time=1 self.update_global_state_matrix(self.nodes, config['communication_radius']) self.update_one_hop_neighbors_lists(self.nodes) self.update_two_hop_neighbors_lists(self.nodes) # Move each node for n in self.nodes: # type: Node n.move() if should_plot: self.plot_nodes(config['communication_radius']) # Build state matrix and neighbor lists # Time=2 self.update_global_state_matrix(self.nodes, config['communication_radius']) self.update_one_hop_neighbors_lists(self.nodes) self.update_two_hop_neighbors_lists(self.nodes) # Make predictions for all nodes for algo in self.algorithms: # MDS calculation n_nodes = len(self.nodes) predicted_distances = np.ones((n_nodes,n_nodes)) * 100 # 50 # -1 # 100 predicted_distances_count = np.ones((n_nodes,n_nodes)) for n in self.nodes: n.one_hop_neighbor_predicted_distances[algo.name()] = {} algo.predict(config, self.nodes, self.current_global_state_matrix) for n in self.nodes: for n2 in n.one_hop_neighbors: predicted_distances[n.index][n2.index] = n.currentP.distance(n2.currentP) predicted_distances[n2.index][n.index] = n.currentP.distance(n2.currentP) predicted_distances_count[n.index][n2.index] += 1 predicted_distances_count[n2.index][n.index] += 1 for n2 in n.two_hop_neighbors: predicted_distances[n.index][n2.index] = n.currentP.distance(n2.currentP) predicted_distances[n2.index][n.index] = n.currentP.distance(n2.currentP) predicted_distances_count[n.index][n2.index] += 1 predicted_distances_count[n2.index][n.index] += 1 X_true = np.array([[p.currentP.x,p.currentP.y] for p in self.nodes]) # Get average predicted_distances = predicted_distances / predicted_distances_count # MDS mds_model = MDS(n_components=2, max_iter=3000, eps=1e-19, dissimilarity="precomputed") mds_positions = mds_model.fit_transform(predicted_distances) # mds_positions = mds_model.fit(predicted_distances).embedding_ # Rotate clf = PCA(n_components=2) X_true = clf.fit_transform(X_true) mds_positions = clf.fit_transform(mds_positions) # Rescale mds_positions *= np.sqrt((X_true ** 2).sum()) / np.sqrt((mds_positions ** 2).sum()) # new_X_true = X_true * np.sqrt((mds_positions ** 2).sum()) / np.sqrt((X_true ** 2).sum()) # new_mds_positions = mds_positions * np.sqrt((X_true ** 2).sum()) / np.sqrt((mds_positions ** 2).sum()) # Scale for i in [0,1]: d_true = X_true[:,i].max() - X_true[:,i].min() d_mds = mds_positions[:,i].max() - mds_positions[:,i].min() mds_positions[:,i] *= (d_true / d_mds) # Rotate clf = PCA(n_components=2) X_true = clf.fit_transform(X_true) mds_positions = clf.fit_transform(mds_positions) for i in range(len(self.nodes)): n1 = self.nodes[i] for j in range(len(self.nodes)): n2 = self.nodes[j] if i != j: print("not the same!") if n1.currentP.distance(n2.currentP) < config['communication_radius']: print("in distance!") # plt.plot([n1.currentP.x, n2.currentP.x], [n1.currentP.y, n2.currentP.y], '--r') # plt.plot([X_true[i,0], X_true[j,0]], [X_true[i,1], X_true[j,1]], '--r') # plt.plot([mds_positions[i,0], mds_positions[j,0]], [mds_positions[i,1], mds_positions[j,1]], ':b') if should_plot: plt.plot(X_true[:,0], X_true[:,1], '^r') plt.plot(mds_positions[:,0], mds_positions[:,1], '*b') for i in range(n_nodes): plt.text(X_true[i,0], X_true[i,1], str(i), color='r') plt.text(mds_positions[i,0], mds_positions[i,1], str(i), color='b') plt.legend(["True positions", "MDS predictions"]) print(X_true) print(mds_positions) err = 0 for i in range(len(X_true)): err = math.sqrt((X_true[i, 0] - mds_positions[i, 0])**2 + (X_true[i, 1] - mds_positions[i, 1])**2) print("Error: ", err) if should_plot: plt.show() return {'error': err}