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 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)
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)
def testgetPaceSecondsFromPossableAndMile(self): r = Route() r.AddSpeed(0, 6) r.AddSpeed(1, 12) r.AddSpeed(2, 18) r.CalculatePossibles() r.printPossables() pace = r.getPaceSecondsFromPossableAndMile(0.1, 0) sys.stdout.write(str(pace) + "\r\n") pace = r.getPaceSecondsFromPossableAndMile(0.1, 0.5) sys.stdout.write(str(pace) + "\r\n") pace = r.getPaceSecondsFromPossableAndMile(0.1, 1) sys.stdout.write(str(pace) + "\r\n") pace = r.getPaceSecondsFromPossableAndMile(0.1, 2) sys.stdout.write(str(pace) + "\r\n\r\n") pace = r.getPaceSecondsFromPossableAndMile(0.15, 0) sys.stdout.write(str(pace) + "\r\n") pace = r.getPaceSecondsFromPossableAndMile(0.15, 0.5) sys.stdout.write(str(pace) + "\r\n") pace = r.getPaceSecondsFromPossableAndMile(0.15, 1) sys.stdout.write(str(pace) + "\r\n") pace = r.getPaceSecondsFromPossableAndMile(0.15, 2) sys.stdout.write(str(pace) + "\r\n")
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
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
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
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)
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
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
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 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 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)
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
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
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 __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)
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
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)
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)
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
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
def GetBestRouteInOrbits(self, source, destination, orbits): routes = list() for orbit in orbits: route = GlobalFunctions.GetRouteNameByProblem(orbit, self) speed = orbit.Speed if self.Speed < orbit.Speed: speed = self.Speed time = orbit.Distance / speed routeObject = Route(route, source, destination, orbit.Name, self, time) routes.extend([routeObject]) routes.sort(key=lambda x: x.Time) return routes[0]
def nouvelle_route(self, ville_depart, ville_arrivee, cout=None): """ Créer une nouvelle route """ if cout is None: # Cout aléatoire coutA = np.random.randint(1, 10) coutB = np.random.randint(0, 8) else: coutA, coutB = cout # Récupérer les villes ville_depart = self.villes[int(ville_depart)] ville_arrivee = self.villes[int(ville_arrivee)] # Créer la route route = Route(ville_depart, ville_arrivee, coutA, coutB) self.routes.append(route)
def CreateRouteObject(self, smallestRoutes, vehicle): routeName = None previousDestination = None for route in smallestRoutes: currentDestination = route.Destination if routeName is None: routeName = route.Name previousDestination = route.Destination else: if previousDestination == currentDestination: currentDestination = route.Source routeName = routeName + ' and ' + currentDestination + ' via ' + route.Orbit return Route(routeName, self.Source, self.Destination, '', vehicle, route.Time)
def findExistingRoute(self, sourceLid, destLid): # returns a Route object if there is already # a route configured for this or None # if not # # do NOT call this when sourceLid and destLid # are on the same leaf switch ! inputLeafSwitch = self.findLeafSwitchFromHostLid(sourceLid) assert inputLeafSwitch != None # find the output switch outputLeafSwitch = self.findLeafSwitchFromHostLid(destLid) assert outputLeafSwitch != None if inputLeafSwitch == outputLeafSwitch: raise Exception( "source and destination lid are connected to the same leaf switch, this is not supported here" ) #---------- # input leaf to spine switch #---------- inputLeafSwitchPort = inputLeafSwitch.getOutputPortForDestination( destLid) if inputLeafSwitchPort == None: # no route defined yet return None # find which spine switch is connected to this port # spineSwitchLid = linkData.getSwitchPortData(inputLeafSwitch.switchLid, inputLeafSwitchPort)['peerLid'] spineSwitchLid = inputLeafSwitch.localLIDs[inputLeafSwitchPort] spineSwitch = self.routingTables[spineSwitchLid] #---------- # spine switch back to output leaf switch #---------- spineSwitchPort = spineSwitch.getOutputPortForDestination(destLid) if spineSwitchPort == None: # no route defined yet on the spine switch # we should actually never come here, this means that # a non-local route was only partially set up ? return None return Route(self.linkData, inputLeafSwitch.switchLid, inputLeafSwitchPort, spineSwitchLid, spineSwitchPort)
def addPlays(self, dict): for play in dict: routes = [] for i in range(4): routes.append(Route(play['routes'][i])) self.routes.append(RouteList(routes)) self.formations.append(play['formation']) self.downs.append(play['down']) self.sides.append(play['strongside']) # optional fields self.clipNumbers.append(play.get('clipnumber', '')) self.progression.append(play.get('yardsTotal', '')) self.intRec.append(play.get('intendedReceiver', '').upper()) self.distance.append(play.get('distance', '')) self.notes.append(play.get('notes', ''))
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]
def draw(self, routes_container): assert isinstance(routes_container, RoutesContainer) self.draw_depot(RoutesContainer.depot) self.draw_points(RoutesContainer.points) previous = 0 # if len(routes_container.details) == 1: # detail = # self.draw_route(Route(routes_container.routes[:detail]).get_full_route()) # self.draw_route(Route(routes_container.routes[detail:]).get_full_route()) for detail in routes_container.details: print(routes_container.routes[previous:previous + detail]) self.draw_route( Route(routes_container.routes[previous:previous + detail]).get_full_route()) previous += detail