def test_lt(self, route1, route2, lt_1): route1 = Route.fromString(route1) route2 = Route.fromString(route2) if lt_1: assert route1 < route2 else: assert not (route1 < route2)
def plot_main(plot_func): # Read and validate command-line arguments if len(sys.argv) != 1 and len(sys.argv) != 3: sys.exit(help()) if len(sys.argv) == 3 and sys.argv[1] != '-o': sys.exit(help()) output_path = sys.argv[2] if len(sys.argv) == 3 else None plt.rcParams['text.latex.preamble'] = [r'\usepackage{lmodern}'] plt.rcParams.update({ 'text.usetex': True, 'text.latex.unicode': True, 'font.family': 'lmodern', 'font.size': 10, 'axes.titlesize': 10 }) fig = plt.figure() route = Route() route.load('/dev/stdin') plot_func(plt, fig, route) plt.tight_layout() if output_path is not None: plt.savefig(output_path, dpi=1000, box_inches='tight') else: plt.show()
def test_base_adj_rib_in_insert(self, populated_adj_rib_in, require_route, empty_adj_rib_in_noiw): r = require_route("40.0.0.0/24") populated_adj_rib_in.insert(r) empty_adj_rib_in_noiw.insert(r) assert len(populated_adj_rib_in) == 4 assert len(empty_adj_rib_in_noiw) == 1 r2 = require_route("40.0.0.0/24") r2.nh = "f" assert len(populated_adj_rib_in[r2]) == 1 assert len(empty_adj_rib_in_noiw[r2]) == 1 assert populated_adj_rib_in.insert(r2)[0] == r2 assert empty_adj_rib_in_noiw.insert(r2)[0] == r2 assert len(populated_adj_rib_in[r2]) == 2 assert len(empty_adj_rib_in_noiw[r2]) == 2 assert populated_adj_rib_in.insert(r2)[0] == r2 assert empty_adj_rib_in_noiw.insert(r2)[0] == None assert len(empty_adj_rib_in_noiw[r2]) == 2 ipaddr = ipaddress.ip_network("40.0.0.0/24") r2 = Route(ipaddr, [1, 2, 3], "K") assert populated_adj_rib_in.insert(r2)[0] == r2 assert empty_adj_rib_in_noiw.insert(r2)[0] == r2 assert len(populated_adj_rib_in[r2]) == 3 assert len(empty_adj_rib_in_noiw[r2]) == 3 ipaddr = ipaddress.ip_network("40.0.0.0/24") r2 = Route(ipaddr, [1, 3], "K") assert populated_adj_rib_in.insert(r2)[0] == r2 assert empty_adj_rib_in_noiw.insert(r2)[0] == r2 assert len(populated_adj_rib_in[r2]) == 3 assert len(empty_adj_rib_in_noiw[r2]) == 4
def test_eq(self, route1, route2, result): route1 = Route.fromString(route1) route2 = Route.fromString(route2) if result: assert route1 == route2 else: assert not (route1 == route2)
def setUp(self): self.gossip_universe = GossipUniverse() # 14 23 34 13 24 33 => 6 minutes self.andy = bus_driver_from(Route([1, 2, 3]), self.gossip_universe) self.cindy = bus_driver_from(Route([4, 3]), self.gossip_universe) self.drivers = [self.andy, self.cindy]
def gerar_rotas(self): distancias = self.__pegar_distancias() rotas = [] for i in range(15): aux = [] for j in range(15): rota = Route(distancias[i][j]) if [i, j] in self.lista_pontos_adj \ or [j, i] in self.lista_pontos_adj: index = 0 try: index = self.lista_pontos_adj.index([i, j]) except ValueError: index = self.lista_pontos_adj.index([j, i]) rota.set_delay_calculator(DelayTime(str(index))) aux.append(rota) rotas.append(aux) return rotas
def setUp(self): self.gossip_universe = GossipUniverse() # - minute stop G1 G2 G3 # # - 1 3 y y n # 3 y y n # 4 n n y # # - 2 1 y y n # 2 y y y # 2 y y y # # - 3 2 y y n # 3 y y y # 3 y y y # # - 4 3 y y n # 1 y y y # 4 y y y # # - 5 3 y y y # 3 y y y # 5 y y y # # - result => 5 self.bob = bus_driver_from(Route([3, 1, 2, 3]), self.gossip_universe) self.alice = bus_driver_from(Route([3, 2, 3, 1]), self.gossip_universe) self.sascha = bus_driver_from(Route([4, 2, 3, 4, 5]), self.gossip_universe) self.drivers = [self.bob, self.alice, self.sascha]
def readRouteTable(): rt = Route() (dbStatus, routes) = rt.readRoutes(con) if (dbStatus == False): return render_template('error.html', error=rt.error) else: return (routes)
def find_best_position(self, route, customer): ##cost, position = return #put in position #check if it's valid #find all possible positions cost_before = route.cost if route.calculate_cost(update=True) != cost_before: print("ERROR MY DAWG COST BEFORE FINDB BEST IN OPTI NEEDS SOME LOOKY LOOK") customers_copy = route.customers[:] n = len(customers_copy) b_position = -1 b_cost = 999999999 for position in range(1,n-1): trial_route = customers_copy[:] trial_route.insert(position, customer) trial_route_ = Route(self.problem, trial_route, get_depot_=False) possible, cost = trial_route_.is_valid() if possible and cost < b_cost: b_position = position b_cost = cost b_cost = b_cost - cost_before return b_cost, b_position
def plot_main(plot_func): # Read and validate command-line arguments if len(sys.argv) != 1 and len(sys.argv) != 3: sys.exit(help()) if len(sys.argv) == 3 and sys.argv[1] != '-o': sys.exit(help()) output_path = sys.argv[2] if len(sys.argv) == 3 else None plt.rcParams['text.latex.preamble']=[r'\usepackage{lmodern}'] plt.rcParams.update({'text.usetex': True, 'text.latex.unicode': True, 'font.family': 'lmodern', 'font.size': 10, 'axes.titlesize': 10}) fig = plt.figure() route = Route() route.load('/dev/stdin') plot_func(plt, fig, route) plt.tight_layout() if output_path is not None: plt.savefig(output_path, dpi=1000, box_inches='tight') else: plt.show()
def findShortestRoute(self, startNode, destinationName): # get routes to process by getting all out going links of the starting node candidateRoutes = Routes( [Route([link]) for link in startNode.getLinks()]) minRoute = None # candiate routes are the routes to process. # they can be empty when no more routes can have distances less than the current minimum distance # or cannot find any more routes while candidateRoutes.len() > 0: # finished routes store the routes connecting start node and end node finishedRoutes = candidateRoutes.getRoutesEndedWithNode( destinationName) _minRoute = finishedRoutes.getMinDistance() minRoute = _minRoute if minRoute is None or ( _minRoute is not None and minRoute.getDistance() > _minRoute.getDistance()) else minRoute # filter out routes having bigger distance than min route candidateRoutes = Routes([ route for route in candidateRoutes.getRoutes() if minRoute is None or route.getDistance() < minRoute.getDistance() ]) # all candidate routes go one step further. Store the new generated routes candidateRoutes = Routes([Route([]).copyFrom(route).addNextLink(link) \ for route in candidateRoutes.getRoutes() for link in self.findByName(route.getLastLink().child).getLinks() \ if not route.hasNode(link.child) or (link.child == destinationName and startNode.name == destinationName)]) return minRoute
def setUp(self): self._solarsystem = Solar_system() #self._planet_1 = None route_1_x = [1000, 0, 0] route_1_v = [0, -1000, 0] route_1 = Route(route_1_x, route_1_v) name_1 = "Aalto-3" mass_1 = 10 state_1 = State.ALIVE self._satellite_1 = Satellite(name_1, route_1, mass_1, state_1) route_1_x = [152100000000, 0, 0] route_1_v = [0, 29780, 0] route_1 = Route(route_1_x, route_1_v) name_1 = "Earth" mass_1 = 5.97237*10**24 diameter = 2*6371000 self._planet_1 = Planet(name_1, route_1, mass_1, diameter) self.pos_test_string = "x:220my:100kmz:20m" self.test_read = Read_planets() test_file = open("test_read.txt") self._solarsystem.read_planets(test_file) test_file.close()
class TestRoute(TestCase): def setUp(self): self.terminal = Station() self.middle_station = Station() self.valid_route = Route( [self.terminal, self.middle_station, self.terminal]) def test_creation_allows_base_case(self): try: terminal = Station() Route([terminal, Station(), terminal]) except ValueError: self.fail("Raised exception with legal constructor arguments") def test_creation_fails_when_first_and_last_station_are_different(self): self.assertRaises(ValueError, Route, [Station(), Station()]) def test_creation_fails_if_consecutive_stations_are_identical(self): fail_station = Station() self.assertRaises(ValueError, Route, [fail_station, fail_station]) def test_go_to_next_station_base_case(self): self.assertTrue(self.valid_route.go_to_next_station()) self.assertEqual(self.middle_station, self.valid_route.current_station) def test_go_to_next_station_fails_when_at_final_station(self): self.assertTrue(self.valid_route.go_to_next_station()) self.assertTrue(self.valid_route.go_to_next_station()) self.assertFalse(self.valid_route.go_to_next_station())
def get_shortest_route(self, start, end): """ Gets the shortest route by given start and end node. For departure, end node must be a runway node. For arrival, end node must be a gate node. Assume the arrival start point is outside of Spot. """ # GEO_MIDDLE_NORTH = {"lat": 37.122000, "lng": -122.079057} # SP1 = Spot("SP1", GEO_MIDDLE_NORTH) if end in self.runway_nodes: if start not in self.depart_routing_table[end]: return None return self.depart_routing_table[end][start] if type(end) == Gate: spot = end.get_spots() # spot = SP1 node_to_spot = self.arrival_routing_table[spot][start] spot_to_gate = self.arrival_routing_table[spot][end] spot_to_gate.reverse() result = Route(start, end, []) result.add_links(node_to_spot.get_links()) result.add_links(spot_to_gate.get_links()) return result raise Exception("End node is not a runway node nor a gate node.")
def __init__(self, states, seconds, inc_support, dec_support): self.states = states self.seconds = seconds self.inc_support = inc_support self.dec_support = dec_support self.best_solution = Route(inc_support, dec_support) self.best_solution.calculate_value()
def constraint_relaxation(batteries, houses): """ Keeps connecting the closest house and battery, then switches routes until constraints are satisfied """ houses_local = houses batteries_local = batteries # distances contains a number of lists, one for each battery, # containing tuples of houses and distances to the corresponding battery distances = [] for battery in batteries_local: unsorted = [] for house in houses_local: route = Route(house, battery) unsorted.append((route.get_length(), house)) sorted_houses = countSort2(unsorted) distances.append(sorted_houses) while len(houses_local) > 0: closest = distances[0][0] id = 0 for i in range(len(distances)): # check the first element of eacht list if it is closer than the # previous one if len(distances[i]) > 0: if distances[i][0][0] < closest[0]: closest = distances[i][0] id = i # connect the closest house batteries_local[id].connect_house(closest[1]) houses_local.remove(closest[1]) for d in distances: for tuple in d: if tuple[1] == closest[1]: d.remove(tuple) return apply_constraints(batteries_local)
def test_with_given_two_route_parents_with_odd_number_of_genes_should_crossover_correctly( self): #ASSET #Route 1 n = 3 coordinates_for_dot_1_of_route_1 = (0, 2) coordinates_for_dot_2_of_route_1 = (2, 1) coordinates_for_dot_3_of_route_1 = (2, 2) dot_1_of_route_1 = Dot(coordinates_for_dot_1_of_route_1) dot_2_of_route_1 = Dot(coordinates_for_dot_2_of_route_1) dot_3_of_route_1 = Dot(coordinates_for_dot_3_of_route_1) dots_route_1 = [dot_1_of_route_1, dot_2_of_route_1, dot_3_of_route_1] route_1 = Route(dots_route_1) #Route 2 coordinates_for_dot_1_of_route_2 = (2, 2) coordinates_for_dot_2_of_route_2 = (0, 2) coordinates_for_dot_3_of_route_2 = (2, 1) dot_1_of_route_2 = Dot(coordinates_for_dot_1_of_route_2) dot_2_of_route_2 = Dot(coordinates_for_dot_2_of_route_2) dot_3_of_route_2 = Dot(coordinates_for_dot_3_of_route_2) dots_route_2 = [dot_1_of_route_2, dot_2_of_route_2, dot_3_of_route_2] route_2 = Route(dots_route_2) #expected_children child_1 = Route([Dot((0, 2)), Dot((2, 1)), Dot((2, 2))]) child_2 = Route([Dot((2, 2)), Dot((0, 2)), Dot((2, 1))]) expected_children = (child_1, child_2) #ACT result_children = crossover(route_1, route_2, n) #ASSERT self.assertEqual(result_children, expected_children)
def test_comparisons(self): shuffled = Route( Edge(i='A', f='B', d=1), Edge(i='D', f='A', d=3), Edge(i='B', f='C', d=1), Edge(i='C', f='D', d=2), ) longer_both = Route(Edge(i='A', f='B', d=1), Edge(i='B', f='C', d=1), Edge(i='C', f='D', d=2), Edge(i='D', f='E', d=3), Edge(i='E', f='F', d=5), Edge(i='F', f='A', d=8)) longer_mag_fewer_stops = Route(Edge(i='A', f='B', d=1), Edge(i='B', f='C', d=2), Edge(i='C', f='A', d=8)) peer = Route(Edge(i='A', f='B', d=1), Edge(i='B', f='C', d=1), Edge(i='C', f='D', d=1), Edge(i='D', f='A', d=4)) more_stops_same_mag = Route(Edge(i='A', f='B', d=1), Edge(i='B', f='C', d=1), Edge(i='C', f='D', d=1), Edge(i='D', f='E', d=1), Edge(i='E', f='A', d=2)) self.assertGreater(longer_both, self.route) self.assertGreater(longer_mag_fewer_stops, self.route) self.assertNotEqual(peer, self.route) self.assertNotEqual(more_stops_same_mag, self.route) self.assertNotEqual(shuffled, self.route)
def visualize(batteries, houses): # Show the route in a grid mng = plt.get_current_fig_manager() mng.full_screen_toggle() plt.grid() for house in houses: plt.plot(house.get_x(), house.get_y(), 'o', color='black', markersize=2) # Iterate over the batteries to find the route with the corresponding house for battery in batteries: plt.plot(battery.get_x(), battery.get_y(), 'X', color='black', markersize=12) for route in battery.get_routes(): # Check if the route selected is optimal, or if the house has # a battery closer by length = route.get_length() optimal = True for battery in batteries: test = Route(route.get_house(), battery) if test.get_length() < length: optimal = False if optimal: routes = [(tup1, tup2) for tup1, tup2 in route.get_coordinates()] plt.plot(*zip(*routes), linewidth=1, linestyle='solid', marker='o', markersize=1, color='blue') plt.pause(0.1) else: routes = [(tup1, tup2) for tup1, tup2 in route.get_coordinates()] plt.plot(*zip(*routes), linewidth=1, linestyle='solid', marker='o', markersize=1, color='red') plt.pause(0.1)
def test_policyvalue_setter(self, addr, path, nh, policy_value): ipaddr = ipaddress.ip_network(addr) pl = PolicyValue(policy_value) route = Route(ipaddr, path, nh) assert route.policy_value.value == 0 route.policy_value = pl assert route.policy_value.value == pl.value assert id(route.policy_value) == id(pl)
def __init__(self, _id): self.id = _id self.route = Route() self.miles_traveled = 0 self.max_speed = 18 # Truck can reach a max speed of 18 MPH. self.max_packages = 16 # Truck can contain a max of 16 packages per route self.completed_route = False self.departure_time = None self.started_delivering = False
def ping(source, connection): """Sends out a message requesting a response from all other nodes in network""" message = "ping" universal = Address("*") route = Route(source, universal, universal) connection.open() connection.write(route.get_path() + message, route.dest) connection.close()
def snap_points(self, points): last_way = None snapped_points = [] last_distance = None # headings before snapping headings = [] for i, p in enumerate(points): if i < len(points) - 1: next_point = points[i + 1] headings.append( Route.get_heading(p.y, p.x, next_point.y, next_point.x)) headings.append(headings[-1]) h_diff = [] for point_index in range(len(points)): point = points[point_index] heading = headings[point_index] # if last_way is not None: # projection = last_way.project(point) # distance = last_way.distance(point) # if 0 <= projection <= 1 and distance < 1.1 * last_distance: # snapped_point = last_way.interpolate(projection) # last_distance = distance # snapped_points += [snapped_point] # continue last_way = self.get_closest_way_with_heading(point, heading) # last_way = self.get_closest_way(point) projection = last_way.project(point) # last_distance = last_way.distance(point) snapped_point = last_way.interpolate(projection) h = WaySet.get_linestring_heading_at_projection( last_way, projection) h_diff += [headings[point_index] - h] snapped_points += [snapped_point] # plt.plot(h_diff) # plt.show() # headings after snapping headings = [] for i, p in enumerate(snapped_points): if i < len(snapped_points) - 1: next_point = snapped_points[i + 1] headings.append( Route.get_heading(p.y, p.x, next_point.y, next_point.x)) headings.append(headings[-1]) return Route.from_points(snapped_points, headings)
def testInitializeRoutes(self, mockCreateRoute): ifacefailover.initializeRoutes(self.routes) assert 3 == mockCreateRoute.call_count expected = [ call(self.defaultRoute, ), call(Route('8.8.8.8', '192.168.1.1', '255.255.255.255', 'eth0'), ), call(Route('8.8.4.4', '192.168.1.1', '255.255.255.255', 'eth0'), ) ] assert expected == mockCreateRoute.call_args_list
def test_base_adj_rib_in_preference_ordering(self, empty_adj_rib_in): ipaddr = ipaddress.ip_network("40.0.0.0/24") r1 = Route(ipaddr, ["F"], "K") ipaddr = ipaddress.ip_network("40.0.0.0/24") r2 = Route(ipaddr, ["F", "2", "3"], "4") assert empty_adj_rib_in.insert(r2)[0] == r2 assert empty_adj_rib_in.insert(r1)[0] == r1 assert empty_adj_rib_in[r2][0] == r2 empty_adj_rib_in.preference_ordering() assert empty_adj_rib_in[r2][0] == r1
def testCreateRouteWithExistingRoute(self, mockGetRoute, mockDeleteRoute, mockAddRoute): existingRoute = Route('0.0.0.0', '192.168.1.1', '0.0.0.0', 'eth0') mockGetRoute.return_value = existingRoute route = Route('0.0.0.0', '192.168.1.1', '0.0.0.0', 'eth0') ifacefailover.createRoute(route) mockGetRoute.assert_called_once_with('0.0.0.0') mockDeleteRoute.assert_called_once_with(existingRoute) mockAddRoute.assert_called_once_with(route)
def parse(self): route = Route() kmldoc = minidom.parse(self.file) placemarks = kmldoc.getElementsByTagName('Placemark') for x in xrange(len(placemarks)): direction = self.getDirection(placemarks[x]) route.addDirection(direction) return route
def loadStops(self): route = Route(self.str_route) # dict_stops = route.loadStopsDict() dict_routes = route.loadRoutesDict() set_allStops = set() for str_routeAbb in dict_routes.keys(): set_allStops = set_allStops.union(dict_routes[str_routeAbb]) self.l_stops = list(set_allStops)
def test_determinisitic_outcome(self): self.policy.SetProbability(.5) # 50% chance to apply. self.policy.SetSeed(2) # Use the pseudo random sequence derived from seed=2. Route(tag="1", title = "1").put() self.assertEqual(0, Route.query().count(3)) self.assertEqual(0, Route.query().count(3)) # Will always be applied before the third query. self.assertEqual(1, Route.query().count(3)) self.policy.SetProbability(0)
def setUp(self): ids = ['a', 'b', 'c', 'd', 'e'] lat = [10, 20, 15, 40, 50] lon = [15, 30, 22.5, 60, 75] self.routes = [1, 1, 2, 2, 3] self.stops = [Stop(ids[i], lat[i], lon[i]) for i in range(len(ids))] s1 = [self.stops[0], self.stops[1]] print(s1) s2 = [self.stops[2], self.stops[3]] self.m1 = MegaStop(ids[0], s1) self.m2 = MegaStop(ids[1], s2) self.route = Route(1, [self.m1, self.m2])
def run(self): while True: modify, rule = self.cmd_queue.get() try: if modify == 'I': Route.exe_rule(modify, rule) elif modify == 'D': Route.exe_rule(modify, rule) elif modify == 'L': pass finally: self.cmd_queue.task_done()
def connect(self, *args, **kargs): """Create and connect a new Route to the Mapper. Usage: .. code-block:: python m = Mapper() m.connect(':controller/:action/:id') m.connect('date/:year/:month/:day', controller="blog", action="view") m.connect('archives/:page', controller="blog", action="by_page", requirements = { 'page':'\d{1,2}' }) m.connect('category_list', 'archives/category/:section', controller='blog', action='category', section='home', type='list') m.connect('home', '', controller='blog', action='view', section='home') """ routename = None if len(args) > 1: routename = args[0] args = args[1:] if '_explicit' not in kargs: kargs['_explicit'] = self.explicit if '_minimize' not in kargs: kargs['_minimize'] = self.minimization route = Route(*args, **kargs) # Apply encoding and errors if its not the defaults and the route # didn't have one passed in. if (self.encoding != 'utf-8' or self.decode_errors != 'ignore') and \ '_encoding' not in kargs: route.encoding = self.encoding route.decode_errors = self.decode_errors if not route.static: self.matchlist.append(route) if routename: self._routenames[routename] = route route.name = routename if route.static: return exists = False for key in self.maxkeys: if key == route.maxkeys: self.maxkeys[key].append(route) exists = True break if not exists: self.maxkeys[route.maxkeys] = [route] self._created_gens = False
def swap_points(r): min_l = r.length() p = r.path[:] for s in subsegments(len(r)): i, j = s j = j % len(p) p[i:j] = reversed(p[i:j]) if Route(p).length() < min_l: r = Route(p) min_l = r.length() else: p = r.path[:] return r
def two_opt_1(index, k=5, max_it=10, improvement_threshold=1e-3, maps=maps): must_list = random.sample(range(len(maps)), k) record = [] for swap_first in must_list: new_index = index[swap_first:] + index[:swap_first] impr = 1e6 for swap_last in range(len(index)): if (swap_first - swap_last) % len(index) < 3: continue a, b, c, d = swap_first, swap_first - 1, swap_last, ( swap_last + 1) % len(index) d2_former = (maps[index[a]]).distance( maps[index[b]]) + (maps[index[c]]).distance(maps[index[d]]) d2_new = (maps[index[c]]).distance( maps[index[b]]) + (maps[index[d]]).distance(maps[index[a]]) diff = d2_former - d2_new if diff > impr: impr = diff swap = swap_last r_temp = Route(maps, two_opt_swap(index, swap_first, swap)) r_temp.distance() r_temp.two_opt(max_it) r_temp.cal_score() record.append(new_index + [r_temp.score, r_temp.d, r_temp.steps]) return record
def crossover(self, mom, dad): size = self.city_graph.n - 1 start, end = sorted([random.randrange(size) for _ in range(2)]) momxo = set(mom.vertices[start:end + 1]) dadxo = set(dad.vertices[start:end + 1]) alice = [i for i in dad.vertices if not i in momxo] bob = [i for i in mom.vertices if not i in dadxo] alice[start:start] = mom.vertices[start:end + 1] bob[start:start] = dad.vertices[start:end + 1] return Route(self.city_graph, alice), Route(self.city_graph, bob)
def __initializeResources(self): self.vpc = VPC(self.cidrBlock) self.igw = IGW() self.igwVpcAssoc = IgwVpcAssoc() self.pubRouteTable = RouteTable("public") self.pubRoute = Route("publicRoute", self.pubRouteTable, self.cidrBlock) self.subnet = Subnet("subnet1", self.cidrBlock, self.az) self.routeTableAssociation = RouteTableAssociation( "public", self.subnet, self.pubRouteTable) self.securitygroup = SecurityGroup("test", self.vpc) self.instance = Ec2Instance("test-name", "ami-12345", "t2.micro", "key.pem", self.subnet, self.securitygroup, False, "192.168.007.007")
def __initializeResources(self): self.vpc = VPC(self.cidrBlock) self.igw = IGW() self.igwVpcAssoc = IgwVpcAssoc() self.pubRouteTable = RouteTable("public") self.pubRoute = Route("publicRoute", self.pubRouteTable, self.cidrBlock) self.subnet = Subnet("subnet1", self.cidrBlock, self.az) self.routeTableAssociation = RouteTableAssociation("public", self.subnet, self.pubRouteTable) self.securitygroup = SecurityGroup("test", self.vpc) self.instance = Ec2Instance("test-name", "ami-12345", "t2.micro", "key.pem", self.subnet, self.securitygroup, False, "192.168.007.007")
def main(): route = Route() # Creamos un objeto ruta # JSON con vectores de pruebas jDirections = [ '{"latitude": 41.967782, "longitude": 2.837736, "speed": 1.3}', '{"latitude": 41.967691, "longitude": 2.837481, "speed": 0.1}', '{"latitude": 41.967657, "longitude": 2.837486, "speed": 1}', '{"latitude": 41.967175, "longitude": 2.836808, "speed": 1.3}', '{"latitude": 41.967418, "longitude": 2.836306, "speed": 0}' ] # Anadimos a la ruta for x in xrange(len(jDirections)): direction = json.loads(jDirections[x], object_hook = as_direction) route.addDirection(direction) # Creamos un manager con la ruta routeMgr = RouteManager(route) # Generamos las ubicaciones exportandolas a kml y csv. locations = routeMgr.applyEffects() exportXml(locations, "std-test.kml") exportCsv(locations, "std-test.csv") # Anadimos multiplicador de pasos y exportamos routeMgr.stepMultiplier = 4 locations = routeMgr.applyEffects() exportXml(locations, "step-test.kml") exportCsv(locations, "step-test.csv") # Anadimos ruido y exportamos routeMgr.noise = 20 locations = routeMgr.applyEffects() exportXml(locations, "step-noise-test.kml") exportCsv(locations, "step-noise-test.csv") # Quitamos multiplicador y dejamos solo ruido routeMgr.stepMultiplier = 0 locations = routeMgr.applyEffects() exportXml(locations, "noise-test.kml") exportCsv(locations, "noise-test.csv")
def _do_trace(self, hostname, seconds, silent): dst_ip = socket.gethostbyname(hostname) self._route = Route(dst_ip) self._tracing = True t0 = time.time() last_id = 0 while self._tracing and time.time() - t0 < seconds: base_id = last_id pkts = [] for ttl in range(1, MAX_TTL + 1): id = base_id + ttl pkts.append(IP(dst=dst_ip, ttl=ttl) / ICMP(id=id)) last_id = id try: ans, unans = sr(pkts, verbose=0, timeout=PACKET_TIMEOUT) except socket.error as e: sys.exit(e) for snd, rcv in ans: # ICMP packet type Echo Reply if rcv.type == 0: # Use the ICMP Echo Reply Identifier field id = rcv[1].id # ICMP packet type Time Exceeded elif rcv.type == 11: # Use the Identifier field in the original ICMP Echo Request id = rcv[3].id # Ignore responses of any other kind (unlikely to happen) else: continue # Check that the received packet is a response to # a packet from the current batch. if id < base_id + 1 or id > base_id + 30: continue ttl = id - base_id ip = rcv.src type = rcv.type rtt = (rcv.time - snd.sent_time) * 1000 self._route[ttl].add_reply(ip, type, rtt) if not silent: os.system('clear') print_statistics(self._route) self._tracing = False
def construct_legs(self): self.legs = [] for i, course_leg in enumerate(self.course.legs): _log.info('Finding paths for course leg: %d' % i) nohitlegs = self.chart.find_paths(course_leg) routes = [] for j, nohitleg in enumerate(nohitlegs): route = Route(nohitleg) if self.valid_route(route, (course_leg.p1, course_leg.p2)): _log.info('Adding valid route: %d' % j) routes.append(route) else: route.save_to_kml('invalid_route_%d.kml' % j) _log.info('Ignoring invalid route: %d' % j) routes.sort(key=lambda r: r.length) for j in xrange(len(routes) - 2, -1, -1): if routes[j] == routes[j + 1]: _log.info('Deleting duplicate route: %d' % (j + 1)) del routes[j] if not routes: raise Exception('Failed to find route on leg %d' % (i + 1)) self.legs.append(routes)
def handle_single_cube(self, pts, rev_pts, timeout=60): if self.find_cube(timeout=20.0): self.load_cube() print verify_loaded_cube(self.robot.laserData) start_time = self.robot.time for cmd in self.driver.followPolyLineG(pts, withStops=True): self.robot.setSpeedPxPa(*cmd) self.robot.update() if (not is_in_loading_zone(self.robot.localisation.pose(), self.robot.last_valid_rfid) and is_path_blocked(self.robot.laserData, self.robot.remissionData)): print "ESCAPING FROM", self.robot.localisation.pose() self.driver.stop() break if self.robot.time - start_time > timeout: print "TIMEOUT", self.robot.time - start_time self.driver.goStraight(-0.3, timeout=10) self.driver.turn(angle=math.radians(90), timeout=10) self.driver.turn(angle=math.radians(-90), timeout=10) self.place_cube() return # demo - game3 experiment self.place_cube() # handle offset in case of blocked path print rev_pts route = Route(pts=rev_pts, conv=DummyConvertor()) _, dist, signed_index = route.findNearestEx(self.robot.localisation.pose()) rev_pts = rev_pts[max(0, abs(signed_index) - 1):] print "cut path", dist, signed_index, rev_pts self.driver.turn(angle=math.radians(180), timeout=30) for cmd in self.driver.followPolyLineG(rev_pts): self.robot.setSpeedPxPa(*cmd) self.robot.update()
class PubVPCCfnGenerator: def __init__(self, cidrBlock, az): self.cidrBlock = cidrBlock self.az = az self.__initializeResources() self.__generateCfnConfiguration() def __initializeResources(self): self.vpc = VPC(self.cidrBlock) self.igw = IGW() self.igwVpcAssoc = IgwVpcAssoc() self.pubRouteTable = RouteTable("public") self.pubRoute = Route("publicRoute", self.pubRouteTable, self.cidrBlock) self.subnet = Subnet("subnet1", self.cidrBlock, self.az) self.routeTableAssociation = RouteTableAssociation("public", self.subnet, self.pubRouteTable) self.securitygroup = SecurityGroup("test", self.vpc) self.instance = Ec2Instance("test-name", "ami-12345", "t2.micro", "key.pem", self.subnet, self.securitygroup, False, "192.168.007.007") def __generateCfnConfiguration(self): self.cfnConfiguration = self.vpc.getVPCTeplate() self.cfnConfiguration += "," self.cfnConfiguration += self.igw.getIGWTemplate() self.cfnConfiguration += "," self.cfnConfiguration += self.igwVpcAssoc.getIgwVpcAssociationTemplate() self.cfnConfiguration += "," self.cfnConfiguration += self.pubRouteTable.getRouteTableTemplate() self.cfnConfiguration += "," self.cfnConfiguration += self.routeTableAssociation.getRouteTableAssociationTemplate() self.cfnConfiguration += "," self.cfnConfiguration += self.pubRoute.getRouteTemplate() self.cfnConfiguration += "," self.cfnConfiguration += self.securitygroup.getSecurityGroupTemplate() self.cfnConfiguration += "," self.cfnConfiguration += self.instance.getEc2InstanceTemplate() def getCfnConfiguration(self): return self.cfnConfiguration
#!/usr/bin/env python2 # coding: utf-8 from route import Route def print_statistics(route): print 'TTL IP Addresses Absolute RTT Relative RTT Relative ZRTT Location' for ttl in route.ttls(exclude_noreply=True): ips = route[ttl].gateway_ips() abs_rtt = '%0.03f ms' % route[ttl].abs_rtt() rel_rtt = '%0.03f ms' % route[ttl].rel_rtt() print '%-3d %-15s %11s %14s %15.3f %s' % (ttl, ips[0], abs_rtt, rel_rtt, route[ttl].rel_zrtt(), route[ttl].gateway(ips[0]).location) for ip in ips[1:]: print ' %-62s %s' % (ip, route[ttl].gateway(ip).location) if route[ttl].is_destination(): break print '' if __name__ == '__main__': route = Route() route.load('/dev/stdin') print_statistics(route)
def __init__(self, **kw): super(EZSTHandler, self).__init__(**kw) self.__local_route = Route() self.__vlan_route = Route()
class EZSTHandler(BaseEZSTHandler): def __init__(self, **kw): super(EZSTHandler, self).__init__(**kw) self.__local_route = Route() self.__vlan_route = Route() def bind(self, host='', port=3257): super(BaseEZSTHandler, self).bind(host, port) self.broadcast('JOIN %s' % (self.uid)) def doList(self, param): if param.upper() != 'VLAN': self.logger.info('Local Routing:\n%s' % (str(self.__local_route))) if param.upper() != 'LOCAL': self.logger.info('Vlan Routing:\n%s' % (str(self.__vlan_route))) def doPing(self, param): ''' PING <host>:<port> ''' address, port = param.split(':') port = int(port) self.logger.info('PING to %s:%d' % (address, port)) self.write('PING', (address, port)) def onPing(self, address, param): self.logger.info('PING from %s' % (str(address))) self.write('PONG', address) def onPong(self, address, param): self.logger.info('PONG from %s' % (str(address))) def onJoin(self, address, uid): if uid != self.uid: self.__local_route.add(uid, address) self.write('OK %s' % self.uid, address) def onOk(self, address, uid): self.__local_route.add(uid, address) self.write('QUERY', address) def onQuery(self, address, param): '''Query for global Unique ID ''' safe_counter = 99 # Not to send peer information more than 99 times. for uid, addr in self.__vlan_route.list(): self.write('PEER %s %s' % (uid, addr), address) if safe_counter > 0: break safe_counter -= 1 def onPeer(self, address, param): # For QUERY uid, sep, addr = param.partition(' ') addr = eval(addr) self.__vlan_route.add(uid, address) if BaseEZSTHandler.check_vlan(self.uid, param): logging.debug('Addr = %s' % (str(addr))) self.write('CONNECT %s' % (self.uid), addr) def onConnect(self, address, param): self.write('SUCCESS %s' % (self.uid), address) def onSuccess(self, address, param): pass def doSend(self, param, from_uid=None): try: to_uid, message = string.split(param, maxsplit=1) except ValueError: to_uid, message = param.strip(), '' address = None nexthops = self.__local_route.get(to_uid) + self.__vlan_route.get(to_uid) if from_uid is None: from_uid = self.uid for nexthop in nexthops: self.write('SEND %s %s %s' % (from_uid, to_uid, message), nexthop) break def onSend(self, address, param): from_uid, to_uid, message = string.split(param, maxsplit=2) if to_uid == self.uid: self.logger.info('SEND from %s: %s' % (address, message)) else: self.doSend('%s %s' % (to_uid, message), from_uid)
def loadTitleToStopDict(self): route = Route(self.str_route) self.dict_titleToStop = route.loadTitleToStopDict()
def test_put_then_get_query(self): key = Route(tag="1", title = "1").put() entities = Route.query(Route.tag == "1").fetch() self.assertEqual(1, len(entities))
def test_insert_entity(self): Route(tag="1", title = "1").put() self.assertEqual(1, len(Route.query().fetch()))
def __init__(self, settings): self.settings = Stores.DEFAULTS Route.__init__(self, settings)
class RouteTracer: def __init__(self): self._route = None self._tracing = False self._thread = None def trace(self, hostname, seconds, silent=False): # Force an exception before launching the tracing thread in case the # hostname provided is unknown. socket.gethostbyname(hostname) if self._thread is not None and self._thread.is_alive(): self._tracing = False self._thread.join() self._thread = Thread(target=self._do_trace, args=(hostname, seconds, silent)) self._thread.start() def _do_trace(self, hostname, seconds, silent): dst_ip = socket.gethostbyname(hostname) self._route = Route(dst_ip) self._tracing = True t0 = time.time() last_id = 0 while self._tracing and time.time() - t0 < seconds: base_id = last_id pkts = [] for ttl in range(1, MAX_TTL + 1): id = base_id + ttl pkts.append(IP(dst=dst_ip, ttl=ttl) / ICMP(id=id)) last_id = id try: ans, unans = sr(pkts, verbose=0, timeout=PACKET_TIMEOUT) except socket.error as e: sys.exit(e) for snd, rcv in ans: # ICMP packet type Echo Reply if rcv.type == 0: # Use the ICMP Echo Reply Identifier field id = rcv[1].id # ICMP packet type Time Exceeded elif rcv.type == 11: # Use the Identifier field in the original ICMP Echo Request id = rcv[3].id # Ignore responses of any other kind (unlikely to happen) else: continue # Check that the received packet is a response to # a packet from the current batch. if id < base_id + 1 or id > base_id + 30: continue ttl = id - base_id ip = rcv.src type = rcv.type rtt = (rcv.time - snd.sent_time) * 1000 self._route[ttl].add_reply(ip, type, rtt) if not silent: os.system('clear') print_statistics(self._route) self._tracing = False def isTracing(self): return self._tracing def toJsonSerializableHash(self): if self._route is None: return {} else: return { 'stillTracing': self._tracing, 'hops': self._route.toJsonSerializableHash() }
import tablib from system import EliteSystem from universe import EliteUniverse from distances import DistanceMatrix from route import Route import pprint universe = EliteUniverse() route = Route(universe) route.findRoute('Aerial') route.show()
class RouteTest(unittest.TestCase): def setUp(self): self.verifier = IcmpRouteVerifier() self.handlers = [LogHandler()] self.route = Route('0.0.0.0', '192.168.1.1', '0.0.0.0', 'eth0', ['8.8.8.8', '8.8.4.4'], 10, self.verifier, {'timeout':2, 'maxRetry':3}, self.handlers, [{}]) def testGetTargetRoutes(self): targetRoutes = self.route.getTargetRoutes() assert 2 == len(targetRoutes) assert Route('8.8.8.8', '192.168.1.1', '255.255.255.255', 'eth0') == targetRoutes[0] assert Route('8.8.4.4', '192.168.1.1', '255.255.255.255', 'eth0') == targetRoutes[1] def testIsRouteIsAvailable(self): mockIsRouteAvailable = MagicMock() mockIsRouteAvailable.return_value = True self.verifier.isRouteAvailable = mockIsRouteAvailable assert self.route.isAvailable() assert 2 == mockIsRouteAvailable.call_count expected = [call('8.8.8.8', timeout=2, maxRetry=3,), call('8.8.4.4', timeout=2, maxRetry=3,)] assert expected == mockIsRouteAvailable.call_args_list def testRouteIsNotAvailable(self): mockIsRouteAvailable = MagicMock() mockIsRouteAvailable.return_value = False self.verifier.isRouteAvailable = mockIsRouteAvailable assert not self.route.isAvailable() assert 2 == mockIsRouteAvailable.call_count expected = [call('8.8.8.8', timeout=2, maxRetry=3,), call('8.8.4.4', timeout=2, maxRetry=3,)] assert expected == mockIsRouteAvailable.call_args_list def testOnSetup(self): mockOnSetup = MagicMock() self.route.handlers[0].onSetup = mockOnSetup self.route.onSetup() mockOnSetup.assert_called_once_with(**{}) def testTearDown(self): mockTearDown = MagicMock() self.route.handlers[0].onTearDown = mockTearDown self.route.onTearDown() mockTearDown.assert_called_once_with(**{}) def testOnConnectionFailed(self): mockOnConnectionFailed = MagicMock() self.route.handlers[0].onConnectionFailed = mockOnConnectionFailed self.route.onConnectionFailed() mockOnConnectionFailed.assert_called_once_with(**{}) def testOnConnectionRestored(self): mockOnConnectionRestored = MagicMock() self.route.handlers[0].onConnectionRestored = mockOnConnectionRestored self.route.onConnectionRestored() mockOnConnectionRestored.assert_called_once_with(**{}) def testOnConnected(self): mockOnConnected = MagicMock() self.route.handlers[0].onConnected = mockOnConnected self.route.onConnected() mockOnConnected.assert_called_once_with(**{}) def testValidationExceptionWhenHandlerKwargsDoNotMatchHandlers(self): try: properties = {'route.primary.gateway':'192.168.1.1' , 'route.primary.iface':'eth0' , 'route.primary.handlers':'["../resources/logHandler.pkl","../resources/logHandler.pkl"]' , 'route.primary.handlerKwargs':"[{}]" } createRoutesFromProperties(properties) self.assertFail() except Exception as e: assert 'Handler and HandlerKwargs mismatch for route 0.0.0.0' == e.message def testCreateRoutesFromProperties(self): properties = {'route.primary.gateway':'192.168.1.1' , 'route.primary.iface':'eth0' , 'route.primary.targets':'8.8.8.8,8.8.4.4' , 'route.primary.verifierDelay':'10' , 'route.primary.verifier':'../resources/icmpRouteVerifier.pkl' , 'route.primary.verifierKwargs':"{'timeout':1, 'maxRetry':2}" , 'route.primary.handlers':'["../resources/logHandler.pkl","../resources/logHandler.pkl"]' , 'route.primary.handlerKwargs':"[{},{}]" , 'route.fona.gateway':'0.0.0.0' , 'route.fona.iface':'ppp0'} routes = createRoutesFromProperties(properties) assert 2 == len(routes) primary = routes[0] assert '0.0.0.0' == primary.destination assert '192.168.1.1' == primary.gateway assert '0.0.0.0' == primary.genmask assert 'eth0' == primary.iface assert ['8.8.8.8', '8.8.4.4'] == primary.targets assert 10 == primary.verifierDelay assert IcmpRouteVerifier() == primary.verifier assert {'timeout':1, 'maxRetry':2} == primary.verifierKwargs assert [LogHandler(), LogHandler()] == primary.handlers assert [{},{}] == primary.handlerKwargs primaryTargetRoutes = primary.getTargetRoutes() assert 2 == len(primaryTargetRoutes) primaryTargetRoute1 = primaryTargetRoutes[0] assert '8.8.8.8' == primaryTargetRoute1.destination assert '192.168.1.1' == primaryTargetRoute1.gateway assert '255.255.255.255' == primaryTargetRoute1.genmask assert 'eth0' == primaryTargetRoute1.iface assert 0 == len(primaryTargetRoute1.targets) assert 0 == primaryTargetRoute1.verifierDelay assert None == primaryTargetRoute1.verifier assert {} == primaryTargetRoute1.verifierKwargs assert [] == primaryTargetRoute1.handlers assert [] == primaryTargetRoute1.handlerKwargs primaryTargetRoute2 = primaryTargetRoutes[1] assert '8.8.4.4' == primaryTargetRoute2.destination assert '192.168.1.1' == primaryTargetRoute2.gateway assert '255.255.255.255' == primaryTargetRoute2.genmask assert 'eth0' == primaryTargetRoute2.iface assert 0 == len(primaryTargetRoute2.targets) assert 0 == primaryTargetRoute2.verifierDelay assert None == primaryTargetRoute2.verifier assert {} == primaryTargetRoute2.verifierKwargs assert [] == primaryTargetRoute2.handlers assert [] == primaryTargetRoute2.handlerKwargs fona = routes[1] assert '0.0.0.0' == fona.destination assert '0.0.0.0' == fona.gateway assert '0.0.0.0' == fona.genmask assert 'ppp0' == fona.iface assert 0 == len(fona.targets) assert 0 == fona.verifierDelay assert None == fona.verifier assert {} == fona.verifierKwargs assert [] == fona.handlers assert [] == fona.handlerKwargs
def __init__(self, settings): self.settings = Products.DEFAULTS Route.__init__(self, settings)
import sys sys.path.append("/vagrant/src/aws_resources") from route import Route from route_table import RouteTable pubRouteTable = RouteTable("public") pubRoute = Route("publicRoute", pubRouteTable, "10.0.1.0/24") pubRouteTemplate = pubRoute.getRouteTemplate() print pubRouteTemplate pvtRouteTable = RouteTable("private") pvtRoute = Route("pvtRoute", pubRouteTable, "10.0.1.0/24", False) #Need to integrate with EC2 instance for that EC2 instance pvtRoute.setNatInstance(None)
def test_put_then_get_by_key(self): key = Route(tag="1", title = "1").put() key.get()
def __init__(self, settings): self.settings = Categories.DEFAULTS Route.__init__(self, settings)
def setUp(self): self.verifier = IcmpRouteVerifier() self.handlers = [LogHandler()] self.route = Route('0.0.0.0', '192.168.1.1', '0.0.0.0', 'eth0', ['8.8.8.8', '8.8.4.4'], 10, self.verifier, {'timeout':2, 'maxRetry':3}, self.handlers, [{}])
def __routes(self): if self._routes is None: data = self.__get_json_attr('routes', agencies=self.id) self._routes = { obj['id']: Route.from_json(obj, self.__route_stops.get(obj['id'], [])) for obj in data } return self._routes
def bootstrap_gtfs(self, gtfs_feed, feedname='unknown', populate=True): # Make sure the GTFS feed is completely loaded. gtfs_feed.preload() # Set onestopId if 'onestopId' not in self.data: self.data['onestopId'] = self.make_onestop( geohash=geom.geohash_features(gtfs_feed.stops()), name=feedname ) feedid = self.onestop() # Override operator Onestop IDs agency_onestop = {} for i in self.operatorsInFeed(): agency_onestop[i['gtfsAgencyId']] = i['onestopId'] # Check for agencies. gtfs_agencies = [] for gtfs_agency in gtfs_feed.agencies(): if populate or gtfs_agency.id() in agency_onestop: gtfs_agencies.append(gtfs_agency) else: # Unknown agency pass if not gtfs_agencies: return # Create TL Stops stops = {} # sort; process all parent stations first. order = [] order += sorted(filter(lambda x:x.location_type()==1, gtfs_feed.stops()), key=lambda x:x.id()) order += sorted(filter(lambda x:x.location_type()!=1, gtfs_feed.stops()), key=lambda x:x.id()) for gtfs_stop in order: # Create stop from GTFS stop = Stop.from_gtfs(gtfs_stop, feedid) # Merge into parent station parent = gtfs_stop.get('parent_station') if parent: stop = gtfs_feed.stop(parent)._tl_ref # Merge with existing stop key = stop.onestop() stop = stops.get(key) or stop stops[key] = stop # Add identifiers and tags gtfs_stop._tl_ref = stop stop.add_identifier(gtfs_stop.feedid(feedid)) # Create TL Routes for gtfs_route in gtfs_feed.routes(): if not gtfs_route.stops(): continue # Create route from GTFS route = Route.from_gtfs(gtfs_route, feedid) # Link to TL Stops for gtfs_stop in gtfs_route.stops(): t = getattr(gtfs_stop, '_tl_ref', None) if t: route.add_child(t) # Maintain reference to GTFS Route gtfs_route._tl_ref = route # Create TL Agencies for gtfs_agency in gtfs_agencies: operator = Operator.from_gtfs( gtfs_agency, feedid, onestop_id=agency_onestop.get(gtfs_agency.id()) ) for gtfs_route in gtfs_agency.routes(): t = getattr(gtfs_route, '_tl_ref', None) if t: operator.add_child(t) # Inelegant. operator._cache_onestop() # Add agency to feed self.add_child(operator)
def __init__(self, settings): self.settings = Reviews.DEFAULTS Route.__init__(self, settings)