def __init__(self, grouping='shuffle', parallelism=1, paraNext=1): self.parallelism = parallelism self.paraNext = paraNext self.processed = parallelism*[0] self.grouping = grouping r = Routing(type=self.grouping) self.routingMethod = r.getRoutingMethod()
def createIncidentToIncidentMatrices(self): distances = {} incidentMap = self.simulation.getActiveIncidents(self.agent) router = Routing() for incidentType, incidents in incidentMap.iteritems(): distances[incidentType] = {} for incidentId, pos in incidents.iteritems(): for incident2Id, pos2 in incidents.iteritems(): if incidentId != incident2Id: if incidentId not in distances[incidentType]: distances[incidentType][incidentId] = {} if incident2Id in distances[ incidentType] and incidentId in distances[ incidentType][incident2Id]: distances[incidentType][incidentId][ incident2Id] = distances[incidentType][ incident2Id][incidentId] else: distance = len( router.route(pos.lat, pos.lon, pos2.lat, pos2.lon)['timecoords']) distances[incidentType][incidentId][ incident2Id] = distance distances[incidentType][incidentId][ incident2Id] = distance return distances
def plot_line(topo, proto, label, color, linestyle='-', linewidth=2): start = time.time() routing = Routing(topo, proto, log) paths = routing.generate_random_permutation_paths() edge_counts = sorted(routing.edge_counts(paths).values()) x = [0] y = [0] for i in range(len(edge_counts)): # format graph properly if i != 0 and edge_counts[i] != edge_counts[i - 1]: x.append(i) y.append(edge_counts[i - 1]) x.append(i) y.append(edge_counts[i]) y.append(edge_counts[-1] + 1) x.append(len(edge_counts) - 1) plt.plot(x, y, color=color, linestyle=linestyle, linewidth=linewidth, label=label) finish = time.time() log.info('{} ran in: {}'.format(label, finish - start))
def run(): custom_path_width = 2 # leave the value 0 and it's calculated using the drone FOV specified # Routing( 2D-array of global coordinates specifying the corners of the map, # plot padding, # user defined path width in meters - used for testing # - leave the value 0 and it's calculated using the drone FOV specified) sohn = Routing(odin_arr, 0.00002, custom_path_width) sohn.get_local_coordinates() sohn.analyze_coordinates() # get_to_route( path limit points, # origo global coordinates, # relay box coordinates, # path functions ) get_to_route(sohn.get_path_limit_points(), sohn.get_origo(), odin_relay_box, sohn.get_path_functions()) # search_route( path width (meters) - if default pass obj.get_path_width as parameter, # path limit points, # origo global points, # path functions, # drone speed (m/s) - default value 1 if 0 is passed as a parameter ) search_route(custom_path_width, sohn.get_path_limit_points(), sohn.get_origo(), sohn.get_path_functions(), 0) # print(cmd_string) cmd_string = go_home(sohn.get_path_limit_points(), odin_relay_box, sohn.get_origo()) parser(cmd_string)
def launch(): """ Starts the Controller: - topo is a string with comma-separated arguments specifying what topology to build. e.g.: 'jellyfish,4' - routing is a string indicating what routing mechanism to use: e.g.: 'ecmp8', 'kshort' """ # NOTE: currently only support jellyfish topology. log.info("Launching Jellyfish controller") # Read out configuration from file. # NOTE: assumes jellyfish has been installed in the home directory. config_loc = 'pox/ext/__jellyconfig' with open(config_loc, 'r', os.O_NONBLOCK) as config_file: log.info("inside") n = int(config_file.readline().split('=')[1]) k = int(config_file.readline().split('=')[1]) r = int(config_file.readline().split('=')[1]) seed = int(config_file.readline().split('=')[1]) routing = config_file.readline().split('=')[1].strip() jelly_topology = topologies["jelly"](random_seed=seed, n=n, k=k, r=r) my_routing = Routing(jelly_topology, routing, log, seed=seed) my_routing.generate_rtable() core.registerNew(JellyfishController, jelly_topology, my_routing)
def test_routing(self): self.test_field_finalization() r = Routing(self.field) ret = r.route(4) self.assertGreaterEqual(ret[0], 1)
def __init__(self, with_reconstruction=True): super(CapsNet, self).__init__() self.with_reconstruction = with_reconstruction self.conv1 = nn.Conv2d(1, 256, 9) self.primary_caps = nn.Conv2d(256, 32 * 8, 9, stride=2) self.digit_caps = Routing(32 * 6 * 6, 10, 8, 16, 32) if with_reconstruction: self.fc1 = nn.Linear(160, 512) self.fc2 = nn.Linear(512, 1024) self.fc3 = nn.Linear(1024, 784)
def find_total_turns(total_data, start_point, end_point, total_train): """ Take total data and proceeding find the smallest turn. """ from routing import Routing ls_instance = setup_all_lines(total_data) path = Routing() path.ls_lines = ls_instance setup_state(path.all_train_history, total_train, start_point) return path.find_smallest_turn()
def _full_simple(self, fn, nocheck=False): field = self.construct_field() blocks = self.parse_blocks(os.path.join(self.test_data_dir, fn)) f = self.construct_force_algo_obj(self.field, self.blocks, self.pins) cid = fn.split("op")[1].split(".")[0] f.step_build(DEBUG) f1 = f.get_debug_field() if DEBUG: fn = draw_field(f1, "schematic_build_{}.pdf".format(cid)) f.step_initial(DEBUG) f2 = f.get_debug_field() if DEBUG: fn = draw_field(f2, "schematic_init_{}.pdf".format(cid)) f.step_main(DEBUG) f3 = f.get_debug_field() if DEBUG: fn = draw_field(f3, "schematic_main_{}.pdf".format(cid)) f.step_last(DEBUG) f4 = f.get_debug_field() if DEBUG: f4.trim_size() fn = draw_field(f4, "schematic_final_{}.pdf".format(cid)) # CHECK IF OVERLAPPING BLOCKS WERE FOUND overlap = f4.has_overlapping_blocks() if overlap: f4.show_blocks(sortkey=("groups", "pos")) f4.trim_size() draw_field(f4, "schematic_final_{}.pdf".format(cid)) else: try: f = f4.to_field() f.optimize_size() f.optimize_block_dirs() r = Routing(f) ret = r.route(4) fn = draw_field(f, "schematic_real_{}.pdf".format(cid)) except RoutingException as e: if not nocheck: print "failed with circuit {}".format(cid) print "continuing due to 'nocheck' == True" else: raise e if not nocheck: self.assertFalse(overlap, "Found overlapping blocks!")
def __init__(self, nodes, edges, minb, maxb, tx_num, tx_min, tx_max): assert nodes > 0 and edges > 0 assert 0 <= minb <= maxb assert 0 < tx_min <= tx_max self.min_balance = minb self.max_balance = maxb self.graph = MyGraph(nodes, edges, minb, maxb) self.MST = nx.minimum_spanning_tree(self.graph.nx_graph, weight='weight', algorithm='prim') self.tx = Transaction(nodes, tx_num, tx_min, tx_max) self.routing = Routing(proxy='weight') self.paths = {} self.stats = Statistics() self.dumper = Dump() self.dumper.dump_files(self.graph, self.tx)
def main(argv): input_dir = argv[1] output_dir = argv[2] for file_name in os.listdir(input_dir): print("The order ", file_name, " is processing...") input_path = os.path.join(input_dir, file_name) with open(input_path, 'r', encoding='utf-8', errors='ignore') as f: message_str = f.read() order = Order(message_str) mypack_obj = mypack.Pack(order) hwpack_obj = Pack(message_str, mypack_obj=mypack_obj) route = Routing(order, pack_obj=hwpack_obj) nondominated_sol_listlist = route.population_global_search2(1400, 7) for sol_list in nondominated_sol_listlist: route.res["solutionArray"].append(route.sol_2_trucklist_Dict[''.join([str(x) for x in sol_list])]) route.save_sols(output_dir) print("The order ", file_name, " is done.")
def createResponderToIncidentMatrices(self): responders = self.simulation.getResponders(self.agent) incidents = self.simulation.getActiveIncidents(self.agent) distances = {} router = Routing() for t, respondersByType in responders.iteritems(): distances[t] = {} for responderId, data in respondersByType.iteritems(): lat, lon = data["route"][0] distances[t][responderId] = {} incidentType = "fire" if t == "fireFighters" else "injury" if t == "ambulances" else "looters" for incident, incidentPos in incidents[incidentType].iteritems( ): distance = len( router.route(lat, lon, incidentPos.lat, incidentPos.lon)['timecoords']) distances[t][responderId][incident] = distance return distances
def __init__(self, port, id): threading.Thread.__init__(self) self.id = id self.w = WifiReal(port, id) self.r = Routing(self.w) self.t = Topology(self.r)
def getRandomPosition(self): lat, lon = convert2LatLon( self.distribution(np.random.uniform(), np.random.uniform())) r = Routing() return r.snapToRoad(lat, lon)
from flask import Flask import pymysql pymysql.install_as_MySQLdb() try: from .routing import Routing except ModuleNotFoundError: from routing import Routing app = Flask(__name__) Routing(app) if __name__ == "__main__": app.run()
print "# ble", index, "pin", pin, ":", selection, "(", subblock[ pin], ")" inputs[index * self.bitgen.inputs + pin - 1] = selection self.bitgen.gen_lb(inputs, functions, flops) if __name__ == '__main__': import sys if len(sys.argv) != 6: sys.stderr.write( "usage: {:s} <placement.out> <routing.out> <netlist.net> <logic.blif>\n" .format(sys.argv[0])) sys.exit(1) placement = Placement(sys.argv[1]) routing = Routing(sys.argv[2]) netlist = NET(sys.argv[3]) blif = BLIF(sys.argv[4]) tracks = int(sys.argv[5]) / 2 bitgen = Bitgen(cluster_size=4, ble_inputs=6, lb_inputs_per_side=4, tracks_per_direction=tracks, mux_size=5) fpga = FPGA(placement, routing, netlist, blif, bitgen) fpga.generate()
import time from graph import Graph get_ipt = True if get_ipt: mesh_id = 225 mesh_mac = "882931169" # mesh_id = 202 # mesh_mac = "-346438966" else: mesh_id = 79 mesh_mac = "-346438577" w = CompWifi(mesh_id, mesh_mac) r = Routing(w) t = Topology(r) def recv_msg(from_mac, msg): print("APP: from {}: {}".format(from_mac, msg)) t.register_recv_msg_handler(recv_msg) class GetIpt(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.ipt = None def run(self): while(True): self.ipt = input()
def __init__(self): self.w = WifiSim() self.r = Routing(self.w) self.t = Topology(self.r) self.t.register_recv_msg_handler(self.recv_msg) self.mac = self.t.mac
def main(version): shared_state = State() topo = Topology(shared_state, version) app = Routing(shared_state, version) app.start_event_loop()
'/createSimulation', 'createSimulation', '/(.+)/connectUser', 'connectUser', '/(.+)/addAgent', 'addAgent', '/(.+)/start', 'startSimulation', '/(.+)/(.+)/assignToIncident', 'assignToIncident', '/(.+)/(.+)/incidents', 'incidents', '/(.+)/(.+)/score', 'score', '/postScore', 'postScore', '/scoreboard', 'scoreboard', '/(.+)/(.+)/responders', 'responders', '/availableSimulations', 'activeSimulations', '/route', 'route', '/images/(.+)', 'images', '/(.+)', 'fileLoader') routing = Routing() manager = Manager() class Application(web.application): def run(self, url="0.0.0.0", port=8080, *middleware): func = self.wsgifunc(*middleware) return web.httpserver.runsimple(func, (url, port)) class disaster: # exampleURL: # http://localhost:1234/disaster def GET(self): page = web.template.frender('html/index.html') return page() class agentDisaster: # exampleURL:
# -*- coding:utf-8 -*- """ author: chuanwu.sun created: 2017-03-10 22:25 e-mail: chuanwusun at gmail.com """ from routing import Routing r = Routing()
""" # NOTE: currently only support jellyfish topology. log.info("Launching Jellyfish controller") # Read out configuration from file. # NOTE: assumes jellyfish has been installed in the home directory. config_loc = 'pox/ext/__jellyconfig' with open(config_loc, 'r', os.O_NONBLOCK) as config_file: log.info("inside") n = int(config_file.readline().split('=')[1]) k = int(config_file.readline().split('=')[1]) r = int(config_file.readline().split('=')[1]) seed = int(config_file.readline().split('=')[1]) routing = config_file.readline().split('=')[1].strip() jelly_topology = topologies["jelly"](random_seed=seed, n=n, k=k, r=r) my_routing = Routing(jelly_topology, routing, log, seed=seed) my_routing.generate_rtable() core.registerNew(JellyfishController, jelly_topology, my_routing) # for debugging if __name__ == '__main__': topo = 'dummy' routing = 'ecmp' my_topology = build_topology(topo) my_routing = Routing(my_topology, routing, log) my_routing.generate_rtable()
def __init__(self): self.brushfire_cffi = Cffi() self.topology = Topology() self.routing = Routing() self.coverage = Coverage() # Origin is the translation between the (0,0) of the robot pose and the # (0,0) of the map self.origin = {} self.origin['x'] = 0 self.origin['y'] = 0 self.resolution = 0.05 self.step = 0 # Load map's translation if rospy.has_param('origin'): translation = rospy.get_param('origin') self.origin['x'] = translation[0] self.origin['y'] = translation[1] if rospy.has_param('resolution'): self.resolution = rospy.get_param('resolution') # Initilize sensor's specs self.sensor_names = [] self.sensor_direction = [] self.sensor_fov = [] self.sensor_range = [] self.sensor_shape = [] self.sensor_reliability = [] self.min_distance = 0 self.navigation_target = 0 # Read sensor's specs self.robot_radius = rospy.get_param('robot_radius') self.sensor_names = rospy.get_param('sensor_names') self.sensor_number = len(self.sensor_names) self.navigation_target = rospy.get_param('navigation_target') self.navigation_pattern = rospy.get_param('navigation_pattern') self.fixed_step = rospy.get_param('fixed_step') for name in self.sensor_names: self.sensor_direction.append( rospy.get_param(name + '/sensor_direction')) self.sensor_fov.append(rospy.get_param(name + '/fov')) self.sensor_range.append(rospy.get_param(name + '/range')) self.sensor_shape.append(rospy.get_param(name + '/shape')) self.sensor_reliability.append( rospy.get_param(name + '/reliability')) self.ogm_topic = '/map' self.ogm = 0 self.ogm_raw = 0 self.ogm_width = 0 self.ogm_height = 0 self.ogm_header = 0 # Flag to wait ogm subscriber to finish self.ogm_compute = False self.gvd = 0 self.brush = 0 self.nodes = [] self.door_nodes = [] self.rooms = [] self.room_doors = [] self.room_type = [] self.room_sequence = [] self.entering_doors = {} self.exiting_doors = {} self.wall_follow_nodes = [] self.wall_follow_sequence = [] self.zig_zag_nodes = [] self.zig_zag_sequence = [] self.simple_nodes = [] self.simple_sequence = [] # Load nodes from json file map_name = rospy.get_param('map_name') filename = '/home/mal/catkin_ws/src/topology_finder/data/' + map_name + '.json' with open(filename, 'r') as read_file: self.data = json.load(read_file) self.nodes = self.data['nodes'] self.door_nodes = self.data['doors'] self.rooms = self.data['rooms'] self.room_doors = self.data['roomDoors'] self.room_type = self.data['roomType'] if 'room_sequence' in self.data: self.room_sequence = self.data['room_sequence'] if 'entering_doors' in self.data: self.entering_doors = { int(k): v for k, v in self.data['entering_doors'].items() } if 'exiting_doors' in self.data: self.exiting_doors = { int(k): v for k, v in self.data['exiting_doors'].items() } if 'wall_follow_nodes' in self.data: self.wall_follow_nodes = self.data['wall_follow_nodes'] if 'wall_follow_sequence' in self.data: self.wall_follow_sequence = self.data['wall_follow_sequence'] if 'zig_zag_nodes' in self.data: self.zig_zag_nodes = self.data['zig_zag_nodes'] if 'zig_zag_sequence' in self.data: self.zig_zag_sequence = self.data['zig_zag_sequence'] if 'simple_nodes' in self.data: self.simple_nodes = self.data['simple_nodes'] if 'simple_sequence' in self.data: self.simple_sequence = self.data['simple_sequence'] self.node_publisher = rospy.Publisher('/nodes', Marker, queue_size=100) self.candidate_door_node_pub = rospy.Publisher('/nodes/candidateDoors', Marker, queue_size=100) self.door_node_pub = rospy.Publisher('/nodes/doors', Marker, queue_size=100) self.room_node_pub = rospy.Publisher('/nodes/rooms', Marker, queue_size=100)