def generate_map(markers=True): route_map = route.RouteMap(width=FLAGS.map_width, height=FLAGS.map_height, edit_pane=False) if FLAGS.input_gpx: gpx = load_gpx(FLAGS.input_gpx) for r in gpx.routes: route_map.add_route(route.Route( name=r.name, points=[route.LatLng(p.latitude, p.longitude) for p in r.points]), static=True) break for t in gpx.tracks: break for i, s in enumerate(t.segments): name = t.name if len(t.segments) > 1: name += f'_{i}' route_map.add_route(route.Route( name=name, points=[route.LatLng(p.latitude, p.longitude) for p in s.points]), static=True) break break elif FLAGS.input_kml: routes = kml_parser.parse_kml(FLAGS.input_kml) for r in routes: import_route(route_map, r, static=True, markers=markers) route_map.fit_bounds() html = route_map.map()._repr_html_() html = html.replace(';padding-bottom:60%', '', 1) html = html.replace(';height:0', f';height:{FLAGS.map_height}px', 1) html = html.replace('data-html=', 'data-html="') html = html.replace(' onload=', '" onload=') with open(FLAGS.output_map_html, 'w') as f: f.write(html)
def process_node(node): if isinstance(node, kml.KML): nodes_to_process.extend(node.features()) elif isinstance(node, kml.Document): for style in node.styles(): if style.id in styles_dict: raise ValueError(f'Conflict in style names: {style.id}') styles_dict[style.id] = style nodes_to_process.extend(node.features()) elif isinstance(node, kml.Folder): nodes_to_process.extend(node.features()) elif isinstance(node, kml.Placemark): if node.geometry.geom_type == 'LineString': # These are exported by my tool. Assume they use styleUrl style = styles_dict[node.styleUrl[1:]] line_style = route.LineStyle() for st in style.styles(): if type(st) is styles.LineStyle: line_style = route.LineStyle( _kml_color_to_rgb(st.color), max(st.width, 2.0)) latlngs = [ route.LatLng(c[1], c[0]) for c in node.geometry.coords ] routes.append( route.Route(name=node.name, points=latlngs, description=node.description, line_style=line_style)) elif node.geometry.geom_type == 'MultiLineString': # These are exported by GAIA gps. latlngs = sum([[route.LatLng(c[1], c[0]) for c in g.coords] for g in node.geometry.geoms], []) first_style = next(node.styles()) line_style = route.LineStyle() for st in first_style.styles(): if type(st) is styles.LineStyle: line_style = route.LineStyle( _kml_color_to_rgb(st.color), max(st.width, 2.0)) routes.append( route.Route(name=node.name, points=latlngs, description=node.description, line_style=line_style)) elif node.geometry.geom_type == 'Point': # ignore pass else: raise ValueError( f'Unknown geometry: {node.geometry.geom_type}') else: raise ValueError(f'Unknown node: f{type(node)}')
def test_city(self): antwerp = city.City('Antwerp', 34, 33) ghent = city.City('Ghent', 54, 34) kortrijk = city.City('Kortrijk', 80, 23) brussels = city.City('Brussels', 62, 44) route01 = rt.Route([antwerp, ghent, kortrijk, brussels, antwerp]) route02 = rt.Route([antwerp, kortrijk, ghent, brussels, antwerp]) route03 = rt.Route([antwerp, ghent, brussels, kortrijk, antwerp]) #population = gen.Population([route01, route02, route03], 3) self.assertEqual(antwerp.Name, 'Antwerp') route01.calculate_fitness() self.assertGreater(route01.Fitness, 0)
def test_breeding(self): city01 = city.City('01', 0, 2) city02 = city.City('02', 4, 5) city03 = city.City('03', 4, 2) city04 = city.City('04', 7, 3) city05 = city.City('05', 1, 6) city06 = city.City('06', 3, 2) city07 = city.City('07', 10, 8) sequence = [city01, city02, city03, city04, city05, city06, city07] mating_sequence = [city03, city01, city04, city07, city05, city06, city02] route01 = rt.Route(sequence) route02 = rt.Route(mating_sequence) child_route = route01.mate(route02) self.assertEqual(len(route01.Sequence), len(child_route.Sequence)) return
def test_asserts(): packet_common.add_missing_methods_to_thrift() route_table = mkrt(constants.ADDRESS_FAMILY_IPV4) # Passing the wrong prefix type to assert_prefix_address_family asserts with pytest.raises(Exception): packet_common.assert_prefix_address_family("1.2.3.0/24", constants.ADDRESS_FAMILY_IPV4) with pytest.raises(Exception): packet_common.assert_prefix_address_family(mkp("1.2.3.0/24"), constants.ADDRESS_FAMILY_IPV6) with pytest.raises(Exception): packet_common.assert_prefix_address_family(mkp("::1.2.3.0/24"), constants.ADDRESS_FAMILY_IPV4) with pytest.raises(Exception): packet_common.assert_prefix_address_family(mkp("1.2.3.0/24"), 999) # Passing the wrong prefix type to the Route constructor asserts with pytest.raises(Exception): _rte = route.Route("1.2.3.0/24", N, []) # Passing the wrong prefix type to get_route asserts with pytest.raises(Exception): _rte = route_table.get_route("1.2.3.0/24", N) # Passing the wrong prefix type to del_route asserts with pytest.raises(Exception): _deleted = route_table.del_route("1.2.3.0/24", N) # The address family of the route must match the address family of the table with pytest.raises(Exception): route_table.put_route(mkr("1111:1111:1111:1111:0000:0000:0000:0000/64", N))
def synthesis(self, target_state, init_state=state.State({'screen': 'init'}), try_count=1, unclean_change=True): logger.info("synthesis try: %d unclean: %s", try_count, unclean_change) logger.info("init state: %s", init_state) logger.info("target state: %s", target_state) if target_state.matches(init_state): return [route.Route()] methods = self.synthesis_attempt(target_state, init_state, no_failed=True, try_count=try_count, unclean_change=unclean_change) if len(methods) < try_count: methods2 = self.synthesis_attempt(target_state, init_state, no_failed=False, try_count=try_count - len(methods), unclean_change=unclean_change) for method2 in methods2: found = False for method in methods: if str(method) == str(method2): found = True break if not found: methods.append(method2) logger.info("synthesis rets: %d", len(methods)) for method in methods: logger.info("\t%s", method) return methods
def breed_population(mating_pool, number_of_trucks, distance_df, origin): """ Will breed a new generation from the mating pool. Ensures that a percent of the best Route objects will make it into new generation. The remainder of the generation has two randomly chosen parent Route objects that are used to breed a new child Route object. :param mating_pool: list, a list of the objects that are available to be chosen as parents. The function will assume that the necessary number of Elite Route objects are the first items in the list. :param number_of_trucks: int, the number of trucks that can be used to stop at all locations. :param distance_df: pandas DataFrame, distance matrix that includes all locations that need to be stopped at. :param origin: str, name of the origin location in the distance_df. :return: list, the list of Route objects to be used as the new population. """ new_population = [] shuffled_pool = random.sample(mating_pool, _population_size) ##maintain elite objects for i in range(_elite_size): elite_route = mating_pool[i] new_population.append(elite_route) for i in range(_population_size - _elite_size): parent_route1 = shuffled_pool[i] parent_route2 = shuffled_pool[_population_size - i - 1] child_route = route.Route(number_of_trucks, distance_df, origin) child_route.breed_routes(parent_route1, parent_route2) new_population.append(child_route) return new_population
def main(): try: print('hello isea') fileDir = os.path.dirname(os.path.realpath(__file__)) motor = Motor.MotorPI(pd.MotorPin) motor.setNeutral() route = Routing.Route() route.initFromFile(os.path.join(fileDir, 'files/route.json')) servopi = ServoPI(pd.ServoPin) tracefilename = 'files/trace' + str( datetime.datetime.now().strftime("%y-%m-%d-%H-%M")) + '.json' tracefilename = os.path.join(fileDir, tracefilename) trace = Gps.TraceThread(tracefilename) trace.start() controller = Controller.Steering(route, servopi, motor) controller.start() controller.join() trace.stopped = True trace.join() Kml.exportToKML(route, os.path.join(fileDir, 'files/trace.json'), os.path.join(fileDir, 'files/route.kml'), os.path.join(fileDir, 'files/trace.kml')) finally: motor.cleanUp()
def preFillDataInRoute(rawData,splitData,data): #counts all the data in data and sends the number of data to route for i in range(0, splitData): data.append(route.Route(i)) #sets the neighbors in the route class for i in rawData: data[int(i[0])].setNeighbor(data[int(i[1])], int(i[2])) data[int(i[1])].setNeighbor(data[int(i[0])], int(i[2]))
def create_route_and_stop_data_structures(): """Creates and returns a list of Route objects and a dictionary of Stop objects based on the subway data rerieved from the MBTA API but reduced to the salient data""" # Filter route data by type 0,1 to retrieve only subway routes # and only include 'long_name' attribute to reduce request size url = '/routes?filter[type]=0,1&fields[route]=long_name' route_data = get_data_from_api(url) route_objs = [] # List to contain all subway Route objects stop_objs = { } # Dictionary to contain all subway Stop objects, with the name as the key for r in route_data: ############### Append to Route list ################ route_id = r['id'] route_name = r['attributes']['long_name'] # Get stop data for each route (a specific route ID must # be referenced in order to get stop data with the route) url = '/stops?include=route&filter[route]={}'.format(route_id) stop_data = get_data_from_api(url) num_stops = len(stop_data) # Append new Route to list route_objs.append(route.Route(route_id, route_name, num_stops)) ############### Add to Stop dictionary ################ # Loop through all stops for each route, and create a dictionary entry for each new Stop. # Note: stops are listed in route-order. for s_ind in range(len(stop_data)): s = stop_data[s_ind] stop_id = s['id'] stop_name = s['attributes']['name'] # If stop not yet in dictionary, add it if stop_name not in stop_objs: stop_objs[stop_name] = stop.Stop(stop_id, stop_name) # Add the route to the stop's list of routes stop_objs[stop_name].add_route(route_name) # Add the connections to the stop's list of connections if s_ind != 0: #if not first stop in route, add previous stop connection prev_stop_name = stop_data[s_ind - 1]['attributes']['name'] stop_objs[stop_name].add_connection( (prev_stop_name, route_name)) if s_ind != len( stop_data ) - 1: #if not last stop in route, add next stop connection next_stop_name = stop_data[s_ind + 1]['attributes']['name'] stop_objs[stop_name].add_connection( (next_stop_name, route_name)) return route_objs, stop_objs
def __init__(self, origin, path, json): """ 初始化Route和Location """ self.route = route.Route(origin, path, json) self.name = path.split('/')[-1] self.destination_loc = self.route.next_loc() self.next_destination_loc = self.route.next_loc() self.location = location.Location()
def test_put_del_route_errors(): kern = kernel.Kernel(log=None, log_id="", table_name="main") if not kern.platform_supported: return # Attempt to add route with nonsense next-hop interface prefix = packet_common.make_ip_prefix("99.99.99.99/32") nhops = [next_hop.NextHop("nonsense", None)] rte = route.Route(prefix, constants.OWNER_S_SPF, nhops) assert not kern.put_route(rte)
def Search(client, value, FB, FP, source, item): #def heuristic(id1,id2): #Need to determine some heuristic for the Completion Conditions eligible_banks = FB[FB[item] > 0][item] OL = {} #Open list CL = {} #Closed list rte = route.Route(path=[source], item=item) OL[rte] = rte.distance while len(OL) > 0: s = datetime.utcnow() rte = min(OL, key=OL.get) del OL[min(OL, key=OL.get)] if rte.exhausted >= value: ##Eventually condition check ## Call route address book etc... print('Found!') rte.ConstructDetails(client, FB, FP) print(rte.path) return rte else: neighbors = list(set(eligible_banks.index) - set(rte.path)) for end in neighbors: exhausted = rte.exhausted exhausted += FB.at[end, item] distance = rte.distance distance += GetDistanceByAddr(rte.path[len(rte.path) - 1], end, FB, FP) / 1609. path = rte.path.copy() + [end] new_rte = route.Route(path=path, distance=distance, exhausted=exhausted, item=item) OL[new_rte] = new_rte.distance e = datetime.utcnow() print(e - s) return None
def __init__(self, node): ## route -> destination, firsthop, distance self.node = node self.routing_table = { self.node: route.Route(node, node, 0) } # Key Node : Value nextHop Node self.link_state_cache = [] # cache of lsm ids # topology keeps a view of the entire network # use priority queue by distance self.topology = {} # keyNode : (distance, destination)
def routesFromRels(relations): routes = {} for rel in relations: if True or rel.osmcSymbol: for lineId in rel.lines: if routes.has_key(lineId): routes[lineId].addSign(rel) else: newRoute = route.Route(lineId, rel) routes[lineId] = newRoute return routes
def getBaseRoutes(self): """ get all permutations of the route""" allRoutesList = [] allRoutes = list(itertools.permutations(self.airports2Visit)) for airport in allRoutes: # Append the home airport to the start and make the tuples into a list allRoutesList.append( route.Route([ self.home, airport[0], airport[1], airport[2], airport[3] ], self.AirportAtlas)) self.allRoutes = allRoutesList return allRoutesList
def test_distance(self): city01 = city.City('01', 0, 2) city02 = city.City('02', 4, 5) city03 = city.City('03', 4, 2) # 1D Horizontal calculation self.assertEqual(4.0, rt.Route.calculate_distance(city01, city03)) # 1D Vertical calculation self.assertEqual(3.0, rt.Route.calculate_distance(city03, city02)) # 2D Pythagoras calculation self.assertEqual(5.0, rt.Route.calculate_distance(city01, city02)) route01 = rt.Route([city01, city02, city03]) route01.calculate_fitness() self.assertLess(0, route01.Fitness) self.assertEqual(12, route01.get_distance()) route02 = rt.Route([city01, city02, city03, city01]) route02.calculate_fitness() self.assertLess(0, route02.Fitness) self.assertEqual(12, route02.get_distance())
def test_put_del_route(): kern = kernel.Kernel(log=None, log_id="", table_name="5") if not kern.platform_supported: return # Put route with one next-hop (with interface but no address) prefix = packet_common.make_ip_prefix("99.99.99.99/32") nhops = [next_hop.NextHop("lo", None)] rte = route.Route(prefix, constants.OWNER_S_SPF, nhops) assert kern.put_route(rte) # Delete route just added assert kern.del_route(prefix) # Put route with one next-hop (with interface and address) prefix = packet_common.make_ip_prefix("99.99.99.99/32") address = packet_common.make_ip_address("127.0.0.1") nhops = [next_hop.NextHop("lo", address)] rte = route.Route(prefix, constants.OWNER_S_SPF, nhops) assert kern.put_route(rte) # Delete route just added assert kern.del_route(prefix) # Put ECMP route with multiple next-hop (with interface and address) prefix = packet_common.make_ip_prefix("99.99.99.99/32") address1 = packet_common.make_ip_address("127.0.0.1") address2 = packet_common.make_ip_address("127.0.0.2") nhops = [next_hop.NextHop("lo", address1), next_hop.NextHop("lo", address2)] rte = route.Route(prefix, constants.OWNER_S_SPF, nhops) assert kern.put_route(rte) # Do we display the ECMP route properly? tab_str = kern.cli_route_prefix_table(5, prefix).to_string() pattern = (r"[|] Table +[|] 5 +[|]\n" r"[|] Address Family +[|] IPv4 +[|]\n" r"[|] Destination +[|] 99\.99\.99\.99/32 +[|]\n" r"[|] Type +[|] Unicast +[|]\n" r"[|] Protocol +[|] RIFT +[|]\n" r"[|] Scope +[|] Universe +[|]\n" r"[|] Next-hops +[|] lo 127\.0\.0\.1 1 +[|]\n" r"[|] +[|] lo 127\.0\.0\.2 1 +[|]\n") assert re.search(pattern, tab_str) is not None # Delete route just added assert kern.del_route(prefix)
def main(domain_type=2): """ main function to call search code """ # 1) Instantiate Specific Domain if domain_type == 2: my_domain = route.Route() else: my_domain = tsp.TSP() # 2) Instantiate the General Search Class my_search = Search(my_domain) # 3) Search my_search.run_search()
def reload_data(): print('reload_data') global route_map route_map = route.RouteMap(width=FLAGS.map_width, height=FLAGS.map_height) if FLAGS.input_gpx: gpx = load_gpx(FLAGS.input_gpx) for r in gpx.routes: route_map.add_route(route.Route( name=r.name, points=[route.LatLng(p.latitude, p.longitude) for p in r.points]), static=True) break for t in gpx.tracks: break for i, s in enumerate(t.segments): name = t.name if len(t.segments) > 1: name += f'_{i}' route_map.add_route(route.Route( name=name, points=[route.LatLng(p.latitude, p.longitude) for p in s.points]), static=True) break break route_map.fit_bounds() elif FLAGS.input_kml: routes = kml_parser.parse_kml(FLAGS.input_kml) for r in routes: import_route(route_map, r, static=True) route_map.fit_bounds() html = route_map.map()._repr_html_() html = html.replace(';padding-bottom:60%', '', 1) html = html.replace(';height:0', f';height:{FLAGS.map_height}px', 1) print(html[:200]) with open('templates/map.html', 'w') as f: f.write(html)
def test_new_generation(self): city01 = city.City('01', 0, 2) city02 = city.City('02', 4, 5) city03 = city.City('03', 4, 2) city04 = city.City('04', 7, 3) city05 = city.City('05', 1, 6) city06 = city.City('06', 3, 2) city07 = city.City('07', 10, 8) genes = [city01, city02, city03, city04, city05, city06, city07] pop_size = 8 routes = [] for i in range(0, pop_size): routes.append(rt.Route(random.sample(genes, len(genes)))) population = gen.Population(routes, pop_size) new_generation = population.breed() self.assertEqual(pop_size, len(new_generation))
def test_shortest_route(self): # define 10 routes each with the same x and y - shortest route would be the sequence of those routes by name genes = [] route_length = 10 for i in range(0, route_length): genes.append(city.City(str(i), i, i)) pop_size = 100 routes = [] for i in range(0, pop_size): routes.append(rt.Route(random.sample(genes, len(genes)))) population = gen.Population(routes, pop_size, pop_size // 2) fastest_route = population.survival_of_the_fittest(30) shortest_distance = math.sqrt((route_length-1)**2 * 2) * 2 # (pythagoras to x,y = 10,10) self.assertAlmostEqual(fastest_route.get_distance(), shortest_distance)
def create_initial_population(number_of_trucks, distance_df, origin): """ Creates an initial population of Route objects with randomized routes. :param number_of_trucks: int, the number of trucks that can be used to stop at all locations. :param distance_df: pandas DataFrame, distance matrix that includes all locations that need to be stopped at. :param origin: str, name of the origin location in the distance_df. :return: list, a list of all Route objects created. """ population = [] for i in range(_population_size): current_route = route.Route(number_of_trucks, distance_df, origin) current_route.create_routes() population.append(current_route) return population
def getOptionalRoutes(self): """ same as above but we do it for the route with one extra airport """ optionalRoutes = [] for airport in self.airports2Visit: routesWithExtraAirport = self.airports2Visit + [airport] # optionalRoutes.append(routesWithExtraAirport) allOptionalRoutes = list( itertools.permutations(routesWithExtraAirport)) for aroute in allOptionalRoutes: if aroute[0] != aroute[1] and aroute[1] != aroute[2] and aroute[ 2] != aroute[3] and aroute[3] != aroute[4]: #print(aroute[0], aroute[1], aroute[2], aroute[3], aroute[4]) optionalRoutes.append( route.Route([ self.home, aroute[0], aroute[1], aroute[2], aroute[3], aroute[4] ], self.AirportAtlas)) self.allRoutes = optionalRoutes return optionalRoutes
def test_mating_pool(self): city01 = city.City('01', 0, 2) city02 = city.City('02', 4, 5) city03 = city.City('03', 4, 2) city04 = city.City('04', 7, 3) city05 = city.City('05', 1, 6) city06 = city.City('06', 3, 2) city07 = city.City('07', 10, 8) genes = [city01, city02, city03, city04, city05, city06, city07] pop_size = 8 elite_size = 3 routes = [] for i in range(0, pop_size): routes.append(rt.Route(random.sample(genes, len(genes)))) population = gen.Population(routes, pop_size, elite_size) mating_pool = population.create_mating_pool() self.assertEqual(len(mating_pool), elite_size)
def gen(config_file, source_image, dest_image): """Generate a fantasy metro system image.""" station_set = stationset.load(config_file) LOG.debug(f"Producing fantasy metro system for {station_set.name}.") num_routes = random.choice(NUM_ROUTES_RANGE) LOG.debug(f"Creating {num_routes} routes.") routes = [] chosen_colors = [] for i in range(num_routes): r = route.Route(station_set, chosen_colors=chosen_colors) chosen_colors.append(r.color) routes.append(r) # Draw metro. metro = Metro(routes=routes, name=station_set.name) LOG.info(f"Drawing metro system for {station_set.name} to {dest_image}") metro.draw(source_image, dest_image)
def make_greedy_route(self, num): ret_route_list = [] for i in range(num): temp_route = self.city_list[:] temp_ret_route = [] temp_city = temp_route.pop(random.randrange(len(temp_route))) temp_ret_route.append(temp_city) for i in range(len(self.city_list) - 1): nearest_city = None shortest_dist = float("inf") for j in range(len(temp_route)): temp_dist = temp_ret_route[-1].temp_get_dist2_to( temp_route[j]) if temp_dist < shortest_dist: nearest_city = temp_route[j] shortest_dist = temp_dist temp_route.remove(nearest_city) temp_ret_route.append(nearest_city) ret_route_list.append(route.Route(temp_ret_route)) return ret_route_list
def debug_draw(system_name): """Draw all stations onto map, to test accuracy of station positions.""" # Load station set and generate a single route. conf = f"{system_name}.yaml" station_set = stationset.load(conf) r = route.Route(station_set) # Do the drawing - skip lines, just do stations. source_image = f"{system_name}.png" dest_image = f"{system_name}-drawn.png" base, ext = os.path.splitext(source_image) copyfile(source_image, dest_image) im = Image.open(dest_image) font = ImageFont.truetype("DejaVuSerif.ttf", 16) draw = ImageDraw.Draw(im) for s in r.full_real: RADIUS = 6 draw.ellipse([s.x - RADIUS, s.y - RADIUS, s.x + RADIUS, s.y + RADIUS], outline="red", fill="red") draw.text((s.x + RADIUS, s.y + RADIUS), s.name, fill="red", font=font) for s in r.full_fantasy: RADIUS = 6 draw.ellipse([s.x - RADIUS, s.y - RADIUS, s.x + RADIUS, s.y + RADIUS], outline="blue", fill="blue") draw.text((s.x + RADIUS, s.y + RADIUS), s.name, fill="blue", font=font) # Save image. im.save(dest_image)
only_messages = unless_error(xml2json.from_messages_only) eai = unless_error(xml2json.from_feed) def output_mode(output_type): def f(request, **kwargs): request["get"]["output_mode"] = output_type return request return f router = route.Router() router.add( route.Route('/search/jobs/<sid>/control', {"POST": only_messages}, 'job_control')) router.add( route.Route('/search/jobs/<sid>/<data_source>', {"GET": job_data}, 'job_data')) router.add( route.Route('/search/jobs/<sid>', { "GET": eai, "DELETE": only_messages }, 'job_info')) router.add( route.Route('/search/jobs', { "GET": eai, "POST": create_job }, 'jobs')) router.add( route.Route('/search/parser',
import route import random import geog import networkx as nx import osmgraph import itertools import geojsonio import json import numpy as np routeGen = route.Route(pool_size=10, nr_mutants=10, nr_of_attempts=100, max_length_path=100, pref_dist=2000) routeGen.import_file('../../maps/waterloo_small.osm') print 'file imported' start_node = random.choice(list(routeGen.map.nodes())) start_node = 2147170547 print('initial start node: '+str(start_node)) routeGen.setup_initial_pool(start_node) # print(routeGen.pool) for i in range(0,20): routeGen.mutation() routeGen.mutation() # routeGen.add_random_cycles(start_node) if i % 2 == 0: routeGen.cut_pool_size2() routeGen.final_cut()