def inversion_mutation(offspring: list) -> list: # aka IVM
        mutated_offspring = []

        for o in offspring:
            route_len = len(o.route_stops)

            cutoff_1 = random.randrange(route_len + 1)
            cutoff_2 = random.randrange(route_len + 1)

            cut_start = min(cutoff_1, cutoff_2)
            cut_end = max(cutoff_1, cutoff_2)

            cut_route = list(reversed(o.route_stops[cut_start:cut_end]))

            leftovers = o.route_stops[:cut_start] + o.route_stops[cut_end:]
            try:
                insert_at = random.randrange(len(leftovers))
            except:
                insert_at = 0

            mutated_o = Route(RouteManager.INSTANCE)
            mutated_o.route_stops = leftovers[:insert_at] + cut_route + leftovers[insert_at:]

            mutated_o.build_spf()

            mutated_offspring.append(mutated_o)

        return mutated_offspring
    def test_Append_station_true( self ):
        """
        Successful append should return True

        """
        r = Route( self.rm, ['A', 'B'] )
        self.assertTrue( r.append_station( 'C' ) )
    def scramble_mutation(offspring: list) -> list: # aka IVM
        mutated_offspring = []

        for o in offspring:
            route_len = len(o.route_stops)

            cutoff_1 = random.randrange(route_len + 1)
            cutoff_2 = random.randrange(route_len + 1)

            cut_start = min(cutoff_1, cutoff_2)
            cut_end = max(cutoff_1, cutoff_2)

            cut_piece = o.route_stops[cut_start:cut_end]
            random.shuffle(cut_piece)

            mutated_o = Route(RouteManager.INSTANCE)

            for i in range(cut_start):
                mutated_o.route_stops.append(o.route_stops[i])

            for s in cut_piece:
                mutated_o.route_stops.append(s)

            for i in range(cut_end, route_len):
                mutated_o.route_stops.append(o.route_stops[i])

            mutated_o.build_spf()

            mutated_offspring.append(mutated_o)

        return mutated_offspring
示例#4
0
    def add_line(self, name, code, stationList):
        line = Line(name, code)
        self.lineList.append(line)

        prevStation = None
        nextStation = None

        stationObjectList = []
        routeObjectList = []

        for i, v in enumerate(stationList):
            name = v['station']
            if name in self.stationMap:
                station = self.stationMap[name]
            else:
                station = Station(name, 0, 0)
                self.stationMap[name] = station
            route = Route(line, prevStation, nextStation)
            prevStation = station
            stationObjectList.append(station)
            routeObjectList.append(route)

        length = len(stationObjectList)

        for i, route in enumerate(routeObjectList):
            if i != length - 1:
                route.nextStation = stationObjectList[i + 1]
                stationObjectList[i].add_routes(route)
 def crossover(self, route_1, route_2):
     child = Route(self.cities)
     start = np.random.randint(len(route_1))
     if start < len(route_1) - 1:
         end = np.random.randint(start + 1,len(route_2))
         s = end - start
         k = 0
         while 0 < (end - start):
             random_city = route_1.get_city(start)
             child.assign_city(k,random_city)
             start += 1
             k += 1
         for i in range(len(route_2)):
             random_city = route_2.get_city(i)
             if random_city not in child.route:
                 child.assign_city(s,random_city)
                 s += 1
     else:
         k = 1
         random_city = route_1.get_city(start)
         child.assign_city(0,random_city)
         for i in range(len(route_2)):
             random_city = route_2.get_city(i)
             if random_city not in child.route:
                 child.assign_city(k, random_city)
                 k += 1
     return child
示例#6
0
def please(n, airport_thing):

    if n < 0 or n > len(airport_thing["list_of_airports"]):
        return 0

    # if you're trying to access a bad index just return

    if Route.calculate_distance(airport_thing["list_of_airports"][n - 1],
                                airport_thing["list_of_airports"]
                                [n - 2]) > airport_thing["plane"].getRange():
        return 0
    # likewise, if you're trying to go somewhere you can't just return

    airport_thing["signature"] += list_of_airports[n].getName(
    ) + ":" + list_of_airports[n + 1].getName()

    # but otherwise, update the airport thing signature

    for name in airport_names:
        if name not in signature or list_of_airports[n].getName() != home:
            continue
        else:
            return airport_thing

    original_airport_thing = dict(airport_thing)

    # we need to keep a copy of the airport thing because in one of the calls we're going to update it, and in another we're not going to

    airport_thing["score"] += Route.calculate_score(
        airport_thing[list_of_airports[n]],
        airport_thing[list_of_airports[n + 1]])

    return min(please(n - 1, original_airport_thing),
               please(n - 1, airport_thing))
def traverse(start_node, subset, flight_record):

    # next time through, start_node is next in subset if not in visited

    flight_record["previously_visited"].append(start_node.getName())

    if flight_record["previous_airport"] == None:
        flight_record["previous_airport"] = start_node
    else:
        flight_record["previous_airport"] = flight_record["current_airport"]
    flight_record["current_airport"] = start_node

    if len(subset) == 0:
        start = flight_record["current_airport"]
        previous = flight_record["previous_airport"]
        score = Route.calculate_score(flight_record["previous_airport"],
                                      flight_record["current_airport"])
        flight_record[
            "accumulated_score"] = flight_record["accumulated_score"] + score
        return flight_record

    for airport in subset:
        start = flight_record["current_airport"]
        previous = flight_record["previous_airport"]
        flight_record = traverse(airport, [
            x for x in stops[airport.getName()]
            if x.getName() not in flight_record["previously_visited"]
        ], flight_record)
        score = Route.calculate_score(previous, start)
        flight_record[
            "accumulated_score"] = flight_record["accumulated_score"] + score

        return flight_record
示例#8
0
    def get_variable_length_route(self) -> Route:
        # Generates a route between random stations, but keeps track of sations inbetween, so that we attempt
        #   to avoid duplicated stations. On avg gives wtt=1000, but the length of the route varies - no idea
        #   how to work with that
        r = Route(self)
        unused_stations = set(list(range(1, len(self.stations) + 1)))

        def _take_one_from_unused(remove=True) -> int:
            elem = random.choice(tuple(unused_stations))
            if remove:
                unused_stations.remove(elem)

            return elem

        stops = [self.stations[_take_one_from_unused() - 1]]

        while len(unused_stations) != 0:
            st_from = stops[-1]
            st_to = self.stations[_take_one_from_unused(False) - 1]

            info = get_path_info(self.graph, self.stations, st_from, st_to)
            for s in info["stations"]:
                unused_stations.discard(s.id)
                stops.append(s)

        r.route_stops = stops
        r.build_spf()

        return r
示例#9
0
    def get_route(self, destination):
        destination = self.get_uid_from_map(destination)
        current_pos = self.get_current();
        
        dest_id = self.get_index_from_uid(destination)
        curr_id = self.get_index_from_uid(current_pos)
        print "dest id = ", dest_id 
        print "curr id = ", curr_id
       

        from Route import Route
        route = Route(curr_id, dest_id, [], [], [])
        path = route.findRoute()

        from Imu import IMU
	imu = IMU()
	print "imu reading = ", imu.get_heading()
	from obstacle import Obstacle
	o = Obstacle()

        print "setting up motors..."
        from Motor import Motor
        motor = Motor(o)
	motor.setup()       

        print "setting up navigation..."
	from navigate import Navigate
        navigator = Navigate(motor,imu)       
	navigator.set_direc(imu)    
        
        for x in range(0,len(path)-1):
            #print (path[x],path[x+1])
	    #navigator.set_direc(imu)
            navigator.navigate(path[x], path[x+1])
示例#10
0
    def simple_inversion_mutation(offspring: list) -> list: # aka SIM
        mutated_offspring = []

        for o in offspring:
            route_len = len(o.route_stops)

            cutoff_1 = random.randrange(route_len + 1)
            cutoff_2 = random.randrange(route_len + 1)

            cut_start = min(cutoff_1, cutoff_2)
            cut_end = max(cutoff_1, cutoff_2)

            mutated_o = Route(RouteManager.INSTANCE)

            for i in range(cut_start):
                mutated_o.route_stops.append(o.route_stops[i])

            for i in range(cut_end - cut_start):
                mutated_o.route_stops.append(o.route_stops[cut_end - i - 1])

            for i in range(cut_end, route_len):
                mutated_o.route_stops.append(o.route_stops[i])

            mutated_o.build_spf()

            mutated_offspring.append(mutated_o)

        return mutated_offspring
示例#11
0
    def test_Append_off_map( self ):
        """
        Attempt to append a Station that does not follow the Route Map
        should return False.

        """
        r = Route( self.rm, ['A', 'B'] )
        self.assertFalse( r.append_station( 'B' ) )
示例#12
0
 def export_gtfs(cls, directory):
     Agency.write_agencies(directory)
     Calendar.write_calendars(directory)
     Stop.write_stops(directory)
     Route.write_routes(directory)
     Trip.write_trips(directory)
     Frequency.write_frequencies(directory)
     Path.write_paths(directory)
示例#13
0
 def import_gtfs(cls, directory):
     Agency.import_agencies(directory)
     Calendar.import_calendars(directory)
     Stop.import_stops(directory)
     Path.import_paths(directory)
     Route.import_routes(directory)
     Trip.import_trips(directory)
     Frequency.import_frequencies(directory)
示例#14
0
	def setUp(self):
		'''
		Sets up the test suite by creating new Route objects before every test is ran
		'''
		cityPair = ['CHI', 'TOR']
		metroPair = ['SHA', 'NYC']
		self.routeA = Route(cityPair, 1337)
		self.routeB = Route(metroPair, 9001)
示例#15
0
    def __init__(self, cities, population_size):
        self.routes = list()
        self.cities = cities
        self.population_size = population_size

        for _ in range(population_size):
            route = Route(self.cities)
            route.generate_route()
            self.routes.append(route)
示例#16
0
    def test_Append_station( self ):
        """
        Precondition: Route ['A', 'B']
        Postcondition: Route ['A', 'B', 'C']

        """
        r = Route( self.rm, ['A', 'B'] )
        r.append_station( 'C' )
        self.assertEqual( r.stations, ['A', 'B', 'C'] )
    def calculate_distance(self):
        distance = 0
        previous_idx = 0
        for detail_idx in sorted(self.details + [len(self.points)]):
            temp_route = Route(self.routes[previous_idx:detail_idx])
            distance += temp_route.calculate_distance()
            previous_idx = detail_idx

        return distance
示例#18
0
 def get_object_from_dict(values):
     route = Route()
     route.name = XmlParser.get_title(values)
     route.tag = XmlParser.get_tag(values)
     latitude_min = RouteXmlParser.get_latitude_min(values)
     latitude_max = RouteXmlParser.get_latitude_max(values)
     longitude_min = RouteXmlParser.get_longitude_min(values)
     longtitude_max = RouteXmlParser.get_longitude_max(values)
     route.bounding_box = [ [latitude_min, latitude_max], [longitude_min, longtitude_max] ]
     
     return route
示例#19
0
    def get_fixed_length_route(self) -> Route:
        # Always gets a route of fixed length of #total stations, but definitely has a lot of duplicate
        #   stations en-route. On avg gives wtt=3000, but it is the best option for crossover methods
        r = Route(self)

        mixed_stops = list(range(1, len(self.stations) + 1))
        random.shuffle(mixed_stops)

        r.route_stops = [self.stations[x - 1] for x in mixed_stops]
        r.build_spf()

        return r
    def readNetworkView(self, filename):
        target = None
        access = []
        routes = []
        tempNodes = {}
        gateway = ""

        with open(filename) as file:
            lines = file.readlines()
            for line in lines:
                line = line.replace("\n", "")
                args = line.split(",")
                if args[0] == "Target":
                    n = Node(args[1], args[2], args[3], args[4], args[4],
                             False, False, False, args[5], args[6])
                    target = n
                    access.append(n)
                    tempNodes[args[1]] = n
                if args[0] == "Server":
                    n = Node(args[1], args[2], args[2], args[3], args[3],
                             False, False, True, args[4], args[5])
                    server = n
                if args[0] == "Node":
                    n = Node(args[1], args[2], args[3], args[4], args[4],
                             False, False, False, args[5], args[6])
                    access.append(n)
                    tempNodes[args[1]] = n
                if args[0] == "Honeypot":
                    hp = Node(args[1], args[2], args[3], args[4], args[5],
                              True, False, False, args[6])
                    access.append(hp)
                    tempNodes[args[1]] = hp
                if args[0] == "Honeyrouter":
                    hr = Node(args[1], args[2], args[2], args[3], args[3],
                              False, True, False, args[4])
                    access.append(hr)
                    tempNodes[args[1]] = hr
                if args[0] == "Route":
                    idxh = 0
                    r = Route(tempNodes[args[1]], tempNodes[args[2]])
                    for h in args:
                        if idxh > 2:
                            r.addHop(tempNodes[h])
                        idxh += 1
                    routes.append(r)
                if args[0] == "Gateway":
                    gateway = tempNodes[args[1]]

        nv = NetworkView(target, access, routes, gateway, server)
        print("Generated network view for " + str(target.decepted_ip_addr) +
              " on port " + str(target.switchPort))
        return nv
示例#21
0
def buildRouteCosts(list_of_airports, home):
    costs = {}

    for airport in list_of_airports:
        costs[airport.getName()] = {}
        get_costs_from = possibilities[airport.getName()]
        for key in get_costs_from:
            costs_key = airport.getName() + ":" + key
            costs[airport.getName()][costs_key] = (Route.calculate_score(
                airport, possibilities[airport.getName()][key]),
                                                   Route.calculate_distance(
                                                       airport, home))
    return costs
   def dijkstraAlg(self, startCity, endCity, adjList):
       '''
       Finds the shortest path between two cities
       '''
       pQueue = Queue.PriorityQueue()
       for adj in adjList[startCity]:
           adj.accumDist = adj.distance
           pQueue.put((adj.accumDist, adj))
       for iter in adjList:
           for adjC in adjList[iter]:
               if adjC.startCity == startCity:
                   adjC.accumDist = adj.distance
                   newAdj = Route(adjC.endCity, adjC.startCity, adjC.accumDist)
                   pQueue.put((adjC.accumDist, newAdj))
       itEdge = pQueue.get()
       adj = itEdge[1]
       while adj.endCity != endCity:
           itEdge[1].visited = True
           for adj in adjList[itEdge[1].endCity]:
               adj.parent = itEdge[1]
               if adj.visited == False:
                   adj.accumDist = adj.parent.accumDist + adj.distance
                   if adj.endCity == endCity:
                       break
                   for iter in adjList[adj.endCity]:
                       if iter.accumDist < adj.accumDist and iter.visited == True:
                           adj.parent = iter
                   pQueue.put((adj.accumDist, adj))
           for iter in adjList:
               for adjC in adjList[iter]:
                   if adjC.endCity == itEdge[1].endCity:
                       newAdj = Route(adjC.endCity, adjC.startCity, adjC.distance)
                       newAdj.parent = itEdge[1]
                       if newAdj.visited == False:
                           newAdj.accumDist = newAdj.distance + newAdj.parent.accumDist
                           if newAdj.startCity == endCity:
                               adj = newAdj
                               break
                           for iter in adjList[newAdj.endCity]:
                               if iter.accumDist < newAdj.accumDist and iter.visited == True:
                                   newAdj.parent = iter 
                           pQueue.put((adjC.accumDist, newAdj))  
 
           itEdge = pQueue.get()
       print 'Done! The path is:'
       print adj.endCity
       print adj.startCity
       while adj.startCity != startCity:
           adj = adj.parent
           print adj.endCity
           print adj.startCity
示例#23
0
 def close(self):
     self._is_open = False
     self._dbname = None
     
     # clear everything
     Agency.clear()
     Calendar.clear()
     Stop.clear()
     Path.clear()
     Route.clear()
     TripRoute.clear()
     Trip.clear()
     Frequency.clear()
     Picture.clear()
示例#24
0
    def get_best_route(self, from_station, to_station, lines):
        route = Route()
        route.from_stop = from_station
        route.to_stop = to_station
        route.stops = 9999
        if len(lines) == 0:
            route.stops = 9999
            return route
        else:
            for each_line in lines:
                line = self.lines[each_line]
                start_index = 0
                stop_index = 0

                for i in range(0, len(line.stations)):
                    if line.stations[i] == from_station:
                        start_index = i
                    elif line.stations[i] == to_station:
                        stop_index = i

                stops = abs(start_index - stop_index)

                if stops < route.stops:
                    route.stops = stops
                    route.line_number = line.line_number

        return route
示例#25
0
    def __init__(self, session, api_key, route_id):
        route = Route(session, route_id)

        self.__start_location = Location(session, route.get_start_location())
        self.__end_location = Location(session, route.get_end_location())

        maps_client = googlemaps.Client(key=api_key)

        now = datetime.now()

        self.__directions_result = maps_client.directions(
            self.__start_location.get_full_address(),
            self.__end_location.get_full_address(),
            mode="driving",
            departure_time=now)[0]
示例#26
0
def two_opt_swap(route: Route, i, k):
    route = route.route
    part_1 = deepcopy(route[:i])
    part_2 = deepcopy(route[i:k])
    part_2.reverse()
    part_3 = deepcopy(route[k:])
    return Route(part_1 + part_2 + part_3)
示例#27
0
 def crossover(cls, route_1, route_2):
     if random.random() <= cls.crossover_rate:
         pivot_1 = random.randint(0, route_1.routes.get_length())
         pivot_2 = random.randint(0, route_1.routes.get_length())
         pivot_1, pivot_2 = sorted([pivot_1, pivot_2])
         crossover_1 = deepcopy(route_1)
         crossover_2 = deepcopy(route_2)
         crossover_1.routes = Route(route_1.routes[:pivot_1] +
                                    route_2.routes[pivot_1:pivot_2] +
                                    route_1.routes[pivot_2:])
         crossover_2.routes = Route(route_2.routes[:pivot_1] +
                                    route_1.routes[pivot_1:pivot_2] +
                                    route_2.routes[pivot_2:])
         return crossover_1, crossover_2
     else:
         return route_1, route_2
示例#28
0
def index():

    context = {"key": api_key, "title": "Map Demo"}
    startLocation = request.form['startLoc']
    endLocation = request.form['endLoc']
    mT = str(request.form.get('_mode'))
    print(str(mT))
    duration = _create_update_CSVFile(startLocation, endLocation)
    rout = Route(filename)
    maps = Map(rout.trackpoints)

    if "fourWheel" in mT:
        COEmmision = (((rout.trackpoints[0][6]) / 17) * 2.31)
    elif "TwoWheel" in mT:
        COEmmision = (((rout.trackpoints[0][6]) / 55) * 2.31)
    else:
        COEmmision = "Yiiykkss !! you made it to 0 "

    #duration = get_duration
    #route = Route()
    result = {
        'Start ': startLocation,
        'Destination ': endLocation,
        'Distace ': rout.trackpoints[0][6],
        'Duration ': duration,
        'Fuel ': "Petrol",
        "Carbon Emmision ": COEmmision
    }
    return render_template("template.html",
                           map=maps,
                           context=context,
                           result=result)
示例#29
0
    def create_routes(self, debug=False):

        if debug:
            # start a timer because it's a long process!!
            start_time, function_name = time.time(), "create_routes"
            print("Starting", function_name)

        # create the routes
        routes = []
        for route_index in range(self.number_of_routes):

            route = np.random.choice(self.number_of_cities,
                                     self.number_of_cities,
                                     replace=False)

            # generate a name
            name = self.name + " number: " + str(route_index)
            route = Route(self.cities, name)

            # tell it where it came from
            routes.append(route)

        # and save them
        self.routes = routes

        # timer because it's a long process!!
        if debug:
            print("Leaving", function_name, "and the process took",
                  time.time() - start_time)
示例#30
0
 def read_graph_from_file(self, directory_files: str):
     for filename in glob.glob(directory_files):
         with open(filename, 'r', encoding='latin-1') as file:
             lines = file.readlines()
             for i in range(0, len(lines) - 1):
                 if lines[i].startswith('*Z'):
                     # riga con l'identificativo univoco della corsa
                     codice, linea = lines[i].split()[1:3]
                     corsa_uid = codice + " " + linea
                 if not (lines[i].startswith('*')
                         or lines[i + 1].startswith('*')):
                     # righe con informazioni sulla tratta della corsa
                     row = lines[i]
                     nextrow = lines[i + 1]
                     ora_partenza = row[39:44]
                     ora_arrivo = nextrow[32:37]
                     ora_prossima_partenza = nextrow[39:44]
                     stazione_partenza = row[0:9]
                     stazione_arrivo = nextrow[0:9]
                     # aggiunta dell'arco tra le due stazioni
                     self.add_edge(
                         stazione_partenza, stazione_arrivo,
                         Route(int(ora_partenza), int(ora_arrivo),
                               corsa_uid))
                     if ora_prossima_partenza.isspace() and not (
                             stazione_arrivo in self.graph.keys()):
                         # caso in cui una stazione finale di arrivo non sia presente come stazione di partenza per qualche tratta
                         self.add_node(stazione_arrivo)
示例#31
0
    def open_routes_file(self, file_name):
        logging.info("Opening routes file: %s" % file_name)

        with open(file_name, newline='') as csvfile:
            reader = csv.DictReader(csvfile)
            # Read all routes info
            for row in reader:
                route = Route(row, self.stops_list)
                self.routes_list.append(route)

        # Create buses for each route
        for route in self.routes_list:
            logging.info("Creating %d buses for route %s" %
                         (route.buses_total, route.name))
            for i in range(route.buses_total):
                bus = Bus(self.bus_count, route, self.stops_list)
                self.bus_count += 1
                bus.start_time = route.time_offset + route.bus_counter * route.frequency
                route.bus_counter += 1
                self.buses_list.append(bus)

        logging.info("Total created buses %d" % len(self.buses_list))

        globalConstants.results['Total_buses'] = len(self.buses_list)
        globalConstants.results['Total_routes'] = len(self.routes_list)
def generate_random_routes_container(points):
    # from klasteryzacja import klasteryzacja
    # _, details = klasteryzacja()
    # sam = Route(points)
    # sam = Route(points)
    sam = Route(sample(points, len(points)))
    details = generate_random_details(points)
    return RoutesContainer(sam, details)
 def get_subroutes(self):
     subroutes = []
     copy_routes = deepcopy(self.routes)
     for nodes in self.details:
         to_add = copy_routes[:nodes]
         del copy_routes[:nodes]
         subroutes.append(Route(to_add))
     return subroutes
示例#34
0
def build_dict_as_dictionaries(list_of_airports, possibilities_lookup, plane):
    for i in range(len(list_of_airports)):
        possibilities_lookup[list_of_airports[i].getName()] = {}
        for j in range(len(list_of_airports)):
            if i != j and Route.calculate_distance(list_of_airports[i], list_of_airports[j]) <= plane.getRange():
                possibilities_lookup[list_of_airports[i].getName()][list_of_airports[j].getName()] = list_of_airports[j]

    return possibilities_lookup
    def readNetworkView(self,filename):
        target = None
        access = []
        routes = []
        tempNodes = {}
        gateway = ""

        with open(filename) as file:
            lines = file.readlines()
            for line in lines:
                line = line.replace("\n","")
                args = line.split(",")
                if args[0] == "Target":
                    n = Node(args[1],args[2],args[3],args[4],args[4],False,False,False,args[5],args[6])
                    target = n
                    access.append(n)
                    tempNodes[args[1]] = n
                if args[0] == "Server":
                    n = Node(args[1],args[2],args[2],args[3],args[3],False,False,True,args[4],args[5])
                    server = n
                if args[0] == "Node":
                    n = Node(args[1],args[2],args[3],args[4],args[4],False,False,False,args[5],args[6])
                    access.append(n)
                    tempNodes[args[1]] = n
                if args[0] == "Honeypot":
                    hp = Node(args[1],args[2],args[3],args[4],args[5],True,False,False,args[6])
                    access.append(hp)
                    tempNodes[args[1]] = hp
                if args[0] == "Honeyrouter":
                    hr = Node(args[1],args[2],args[2],args[3],args[3],False,True,False,args[4])
                    access.append(hr)
                    tempNodes[args[1]] = hr
                if args[0] == "Route":
                    idxh=0
                    r = Route(tempNodes[args[1]],tempNodes[args[2]])
                    for h in args:
                        if idxh > 2:
                            r.addHop(tempNodes[h])
                        idxh+=1
                    routes.append(r)
                if args[0] == "Gateway":
                    gateway = tempNodes[args[1]]

        nv = NetworkView(target,access,routes,gateway,server)
        print("Generated network view for " +  str(target.decepted_ip_addr) + " on port " + str(target.switchPort))
        return nv
示例#36
0
    def open_routes_file(self, file_name):
        logging.info("Opening routes file: %s" % file_name)

        with open(file_name, newline='') as csvfile:
            reader = csv.DictReader(csvfile)
            # Read all routes info
            for row in reader:
                route = Route(row, self.stops_list)
                self.routes_list.append(route)
示例#37
0
    def swap_mutation(offspring: list) -> list: # aka EM
        mutated_offspring = []

        for o in offspring:
            route_len = len(o.route_stops)

            swap_pos_1 = random.randrange(route_len)
            swap_pos_2 = random.randrange(route_len)

            mutated_o = Route(RouteManager.INSTANCE)
            mutated_o.route_stops = [ s for s in o.route_stops]

            temp = mutated_o.route_stops[swap_pos_1]
            mutated_o.route_stops[swap_pos_1] = mutated_o.route_stops[swap_pos_2]
            mutated_o.route_stops[swap_pos_2] = temp 

            mutated_offspring.append(mutated_o)

        return mutated_offspring
示例#38
0
 def setRouteInitialNode(self):
     """
     Inicializar ruta con nodo de inicio.
     """
     route = Route(
         self.nodeStart.name,
         self.calculateRouteValue(0, self.nodeStart.estimatedCost), 0,
         self.iteration, self.nodeStart)
     self.routeslist.append(route)
     self.iterationList[self.iteration] = self.routeslist
示例#39
0
def build_dict(list_of_airports, possibilities_lookup, plane):
    for i in range(len(list_of_airports)):
        possibilities_lookup[list_of_airports[i].getName()] = []
        for j in range(len(list_of_airports)):
            if i != j and Route.calculate_distance(
                    list_of_airports[i],
                    list_of_airports[j]) <= plane.getRange():
                possibilities_lookup[list_of_airports[i].getName()].append(
                    list_of_airports[j])

    return possibilities_lookup
def build_dp(n, fr):
    dp[0] = 0
    for i in range(1, n):
        min_cost = uint(2 >> 63) + 1
        min_candidate = None
        for candidate in expand(fr.current, fr.visited, fr.input):
            cost = Route.calculate(fr.current, candidate)
            if min_cost > cost:
                min_cost = cost
                min_candidate = candidate
        ret_cost = Route.calculate_return_path(candidate, fr.route)
        clone_fr = clone(fr)
        clone_fr.route = clone_fr.route.add(min_candidate)
        clone_fr.visited.add(min_candidate)
        clone_fr.current = min_candidate
        last = fr.last
        home = fr.input.first()
        fr = clone_fr
        dp[i] = min(dp[i - 1] + ret_cost,
                    dp[i - 1] + cost(candidate, last) + cost(last, home))
示例#41
0
    def generateRoutes(self, ammount=20000, alpha=0.2, maxLoops =300000 ):
        'gera N rotas randomicas'
        random.seed(42)
        self.routes = []
        randomRange = int((len(self.customers)-1) * alpha)
        customers = self.customers[1::]
        customersIgnored = []
        route = Route(self.customers[0])
        def sortFunc(c): return c.distanceOf(route.customers[-1])
        customers.sort(key=sortFunc)
        it = 0
        while(len(self.routes) < ammount):
            it += 1
            if it == (maxLoops/2):
                print "Atingindo numero maximo de execucoes. abrindo alpha"
                randomRange = len(customers)-1
            if it > maxLoops:
                print "Maximo de execucoes sem resultados atingido.", len(self.routes), "rotas geradas"
                break

            i = random.randint(
                0, randomRange)
            nextCustomer = customers[i % len(customers)]
            if(route.canAddCustomer(nextCustomer, self.capacity)):
                route.addCustomer(nextCustomer)
                customers.remove(nextCustomer)
                customers.extend(customersIgnored)
                customersIgnored = []
                customers.sort(key=sortFunc)
            else:
                customersIgnored.append(nextCustomer)
                customers.remove(nextCustomer)

            if(len(customers) == 0):
                route.closeRoute()
                if(self.addRoute(route, it=it)):
                    it = 0
                route = Route(self.customers[0])
                customers.extend(customersIgnored)
                customersIgnored = []

                if(len(customers) == 0):
                    customers = self.customers[1::]
                customers.sort(key=sortFunc)
示例#42
0
    def get_cheapest_route(self):
        # calculates the cost of each possible route and returns the cheapest route (and its cost)
        if self.__error is not None:                                  # if there are no valid routes for this itinerary
            return None, 10 ** 10
        lowest_cost = 10 ** 10                        # method will return this number if itinerary cannot be completed
        self.route_list = self.build_route_list()
        self.cheapest_route = None

        for route in self.route_list:
            total_cost_of_stopovers = self.__stopover_cost * (len(route) - len(self.__airport_list))
            try:
                current_route = Route(route,
                                      self.__aircraft_range,
                                      self.__airport_atlas,
                                      self.__currency_table,
                                      self.__empty_tank,
                                      total_cost_of_stopovers)
            except ImpossibleRouteError:
                continue                                              # this route has a leg that cannot be completed
            else:
                current_route_cost = current_route.get_cost_of_route()
                if current_route_cost < lowest_cost:
                    self.cheapest_route = current_route
                    lowest_cost = current_route_cost
        if lowest_cost == 10 ** 10:                                   # if itinerary cannot be completed
            print("Aircraft has insufficient range to complete this itinerary.")
            print("Consider using a larger aircraft or adding a fuel stop to the list of hubs.")
            self.__error = "Aircraft has insufficient range to complete this itinerary." \
                           "\nConsider using a larger aircraft or adding a fuel stop to the list of hubs."
            self.cheapest_route = None
        else:
            print()
            print(self.cheapest_route)
            self.cheapest_route.print_costs()
            print()
        self.lowest_cost = lowest_cost
        return self.cheapest_route, lowest_cost
示例#43
0
文件: Trip.py 项目: line72/subte
    def import_trips(cls, directory):
        from Route import Route
        from Calendar import Calendar
        from TripRoute import TripRoute
        from Path import Path
        from Stop import Stop

        try:
            f = open(os.path.join(directory, 'trips.txt'), 'rb')
            reader = csv.reader(f)

            mappings = {'route_id': ('route', lambda x: Route.get_by_gtfs_id(x)),
                        'service_id': ('calendar', lambda x: Calendar.get_by_gtfs_id(x)),
                        'trip_id': ('name', lambda x: x),
                        'trip_headsign': ('headsign', lambda x: x),
                        'direction_id': ('direction', lambda x: int(x) if x else 0),
                        'shape_id': ('path', lambda x: Path.get_by_gtfs_id(x)),
            }

            # create a headers with an index
            headers = reader.next()
            r_headers = dict([(x, i) for i, x in enumerate(headers)])

            for l2 in reader:
                if len(l2) != len(headers):
                    print >> sys.stderr, 'Invalid line', l2, headers
                    continue
                
                kw = {}
                for i, a in enumerate(l2):
                    key = headers[i]
                    if key in mappings:
                        kw[mappings[key][0]] = mappings[key][1](BaseObject.unquote(a))
                # create the trip route
                trip_route = TripRoute(**kw)
                # set the id
                trip_route.gtfs_id = BaseObject.unquote(l2[r_headers['trip_id']])
                # create a trip
                trip = trip_route.add_trip()
                trip.gtfs_id = BaseObject.unquote(l2[r_headers['trip_id']])

            # go through the list again and set block ids
            #!mwd - I'm not sure how to do this. We link
            #  blocks by trip ids, but block ids are 
            #  random in gtfs, so we have no way to link
            #  them back

        except IOError, e:
            print >> sys.stderr, 'Unable to open trips.txt:', e
示例#44
0
class TestRoute(unittest.TestCase):
	'''
	A unit test suite for the Route class.
	'''

	
	def setUp(self):
		'''
		Sets up the test suite by creating new Route objects before every test is ran
		'''
		cityPair = ['CHI', 'TOR']
		metroPair = ['SHA', 'NYC']
		self.routeA = Route(cityPair, 1337)
		self.routeB = Route(metroPair, 9001)

	def test_constructor(self):
		'''
		Tests the constructor of the Route class by checking if all the values passed into the constructor
		match all of the object's instance variables
		'''
		self.assertEqual('CHI', self.routeA.ports[0])
		self.assertEqual('TOR', self.routeA.ports[1])
		self.assertEqual(1337, self.routeA.distance)
		self.assertEqual('SHA', self.routeB.ports[0])
		self.assertEqual('NYC', self.routeB.ports[1])
		self.assertEqual(9001, self.routeB.distance)

	def test_set_departure_city(self):
		'''
		Tests set_departure_city() by changing the departure city of one route and checking if the change
		applied, then attempting to change the departure city to an invalid input (nothing should happen).
		'''
		self.assertEqual(self.routeA.set_departure_city('TES'), True)
		self.assertEqual(self.routeB.set_departure_city({1:'adfhsdfhy'}), False)
		self.assertEqual(self.routeA.ports[0], 'TES')
		self.assertEqual(self.routeB.ports[0], 'SHA')

	def test_set_arrival_city(self):
		'''
		Tests set_arrival_city() by changing the arrival city of one route and checking if the change
		applied, then attempting to change the arrival city to an invalid input (nothing should happen).
		'''
		self.assertEqual(self.routeB.set_arrival_city('TIN'), True)
		self.assertEqual(self.routeA.set_arrival_city(64386), False)
		self.assertEqual(self.routeB.ports[1], 'TIN')
		self.assertEqual(self.routeA.ports[1], 'TOR')

	def test_set_distance(self):
		'''
		Tests set_distance() by changing the distance of one route and checking if the change
		applied, then attempting to change the distance to an invalid input (nothing should happen).
		'''
		self.assertEqual(self.routeA.set_distance(50256), True)
		self.assertEqual(self.routeB.set_distance([1234, 1235]), False)
		self.assertEqual(self.routeA.distance, 50256)
		self.assertEqual(self.routeB.distance, 9001)
    def generatgeView(self,rHosts,subnetSpace,targetPort,NCDSPort,HoneyPort,numSubnets,minHP,maxHP,Strategy):

        self.targetsubnet = numSubnets
        self.lowerSubnet = numSubnets/2
        self.upperSubnet = 0
        #generate specified number of subnets
        for s in range(1,numSubnets):
            self.getAvaiSubnet(numSubnets)

        hosts=[]
        #assign hosts to subnets, and deceive their data
        for k in rHosts.keys():
            if k!=NCDSPort and k!=HoneyPort:
                #create new host object
                realip=rHosts[k].split("/")[0]
                realmac=rHosts[k].split("/")[1]
                if k==targetPort:
                    self.target=Host(self.getShortnameHost(),realip,realmac,k)
                    #get subnet address for target
                    self.target=self.setAvailableSubnetAddress(subnetSpace,numSubnets,self.target,targetPort)
                    #print(str(self.target.deceptiveIP))
                else:
                    host=Host(self.getShortnameHost(),realip,realmac,k)
                    #get subnet address for host
                    host=self.setAvailableSubnetAddress(subnetSpace,numSubnets,host,targetPort)
                    #print(str(host.deceptiveIP))

        #assign honeypots to subnets
        realHoneyIP=rHosts[HoneyPort].split("/")[0]
        realHoneyMac=rHosts[HoneyPort].split("/")[1]
        for subKey in self.subnetList.keys():
            numHoneypots=random.randint(minHP,maxHP)
            for hp in range(1,numHoneypots):
                subnet=self.subnetList[subKey]
                hpAddr=self.getAvaiHoneypotforSubnet(subnet)
                honeyAddr=str(subnetSpace[:-2]) + "." + str(subnet.number) + "." + str(hpAddr)
                honeypot=Honeypot(self.getShortnameHoneypot(),realHoneyIP,realHoneyMac,honeyAddr,self.randMac(),HoneyPort)
                self.subnetList[subnet.number].honeypots.append(honeypot)
                #print("Honeypot " + honeyAddr)

        #create honeyrouters
        routerMac=self.randMac()
        targetSubnet = int(self.target.deceptiveIP.split(".")[2])

        subnet=self.subnetList[targetSubnet]
        subnetAddr=str(subnetSpace[:-2]) + "." + str(subnet.number) + ".1"
        hr=Honeyrouter(self.getShortnameHoneyrouter(),subnetAddr,routerMac,NCDSPort)
        subnet.honeyrouter.append(hr)
        gateway=hr.shortName
        self.subnetList[subnet.number]=subnet
        self.honeyrouterList.append(hr)

        for subKey in self.subnetList.keys():
            subnet=self.subnetList[subKey]
            if subnet.number != targetSubnet:
                subnetAddr=str(subnetSpace[:-2]) + "." + str(subnet.number) + ".1"
                hr=Honeyrouter(self.getShortnameHoneyrouter(),subnetAddr,routerMac,NCDSPort)
                subnet.honeyrouter.append(hr)
                self.subnetList[subKey]=subnet
                self.honeyrouterList.append(hr)



        #generate routes
        numhops=1
        for subKey in self.subnetList.keys():
            subnet=self.subnetList[subKey]
            targetSubnet = int(self.target.deceptiveIP.split(".")[2])

            if subnet.number != targetSubnet:
                numhops+=1
                #numhops=random.randint(2,networkDiameter)
                hostIdx=0
                for host in subnet.hosts:
                    r=Route(self.target,host)
                    hostSubnet = int(host.deceptiveIP.split(".")[2])
                    #hops = int(math.fabs(hostSubnet-targetSubnet))

                    #max sub dist min hop dist
                    if Strategy=="minhop_maxsub":
                        hops = numSubnets - hostSubnet

                    if Strategy=="maxhop_maxsub":
                    #max sub dist max hop dist
                        hops = hostSubnet

                    for hop in range(0,hops):
                        r.addHop(self.honeyrouterList[hop])
                    self.routeList.append(r)
                    host.distance=hops
                    #subnet.hosts.insert(hostIdx,host)
                    #hostIdx+=1
                for honeypot in subnet.honeypots:
                    r=Route(self.target,honeypot)
                    for hop in range(0,numhops-1):
                        r.addHop(self.honeyrouterList[hop])
                    self.routeList.append(r)
            else:
                for host in subnet.hosts:
                    r=Route(self.target,host)
                    self.routeList.append(r)
                for honeypot in subnet.honeypots:
                    r=Route(self.target,honeypot)
                    self.routeList.append(r)

        #set gateway


        printer = NetworkPrinter()
        realhosts = printer.printView(self.target,self.subnetList,self.routeList,targetPort,gateway)
        #for printhost in realhosts:
            #print("realhosts.append(\"" + printhost + "\")")
        return (realhosts, self.targetsubnet)
示例#46
0
                        sequence = int(coord_node.get('sequence', -1))
                        lat = float(coord_node.get('lat', 0.0))
                        lon = float(coord_node.get('lon', 0.0))
                        coords.append((lat, lon))
                    except Exception, e:
                        print >> sys.stderr, 'Invalid coordinate path %s: %s' % (name, e)

                try:
                    p = Path(name = name, coords = coords)
                    p.path_id = int(path_id)
                    p.gtfs_id = gtfs_id
                except Exception, e:
                    print >> sys.stderr, 'Error loading path', name, e

            for route_node in tree.getroot().findall('Route'):
                route_id = route_node.get('id', Route.new_id())
                gtfs_id = route_node.get('gtfs_id', None)
                agency_id = route_node.findtext('agency_id')
                short_name = route_node.findtext('short_name')
                long_name = route_node.findtext('long_name')
                description = route_node.findtext('description')
                route_type = route_node.findtext('route_node')
                url = route_node.findtext('url')
                color = route_node.findtext('color')
                text_color = route_node.findtext('text_color')

                agency_id = int(agency_id)
                r = Route(agency = Agency.get(agency_id),
                          short_name = short_name, long_name = long_name,
                          description = description, route_type = route_type,
                          url = url, color = color, text_color = text_color)