def loadFromFile(self, verticeslist, roadlists): pass self.vertices = [] self.roads = [] for vcortege in verticeslist: self.vertices.append(Vertex.newVertex(vcortege[0], vcortege[1], self.net)) i = 0 for cortege in roadlists: n = cortege[0] bool = cortege[1] rlist = cortege[2] for vertex in self.vertices: if vertex.x() == rlist[0][0] and vertex.y() == rlist[0][1]: begv = vertex break road = Road(begv, self.net, n, bool) for vertex in self.vertices: if vertex.x() == rlist[-1][0] and vertex.y() == rlist[-1][1]: endv = vertex break points = [] for cortege in rlist: points.append(Point(cortege[0], cortege[1])) road.found(points, endv) self.roads.append(road)
def parseXml(node): from Road import Road child = node.firstChild road = None if (child.tagName == Road.getXmlName()): road = Road.parseXml(child) return road
def headingError(self, s = Sample()): s2 = Road.Segment() s2 = env.road.getSegment(s.simcarRoadIndex) s1 = Road.Segment() s1 = self.env.road.getSegment(s.simcarRoadIndex - 1) rh = Position() rh = rh.normalize() return (abs(rotAngle(rh.x, rh.z) - rotAngle(s.simcarHeading.x, s.simcarHeading.z)))
def __init__(self, length, prob, keepalive, wait_weight): self.NSRoad = Road(length,prob) self.EWRoad = Road(length,prob) self.keepalive = keepalive self.total_reward = 0 self.length = length self.prob = prob self.end = False self.wait_weight = wait_weight
def addRoad(self, position1, position2): if position1[0] == position2[0]: for i in range(position1[1], position2[1] + 1): if self.checkIfPositionIsEmpty([position1[0], i]): element = Road(position1[0], i) self.mapElements.append(element) elif position1[1] == position2[1]: for i in range(position1[0], position2[0] + 1): if self.checkIfPositionIsEmpty([i, position1[1]]): element = Road(i, position1[1]) self.mapElements.append(element)
def __init__(self, numRoads, length, prob, keepalive, wait_weight): self.NSRoads = [Road(length, numRoads, prob)] * numRoads self.EWRoads = [Road(length, numRoads, prob)] * numRoads self.intersection = [[0] * numRoads] * numRoads self.keepalive = keepalive self.total_reward = 0 self.numRoads = numRoads self.length = length self.prob = prob self.end = False self.wait_weight = wait_weight self.numSteps = 0
class Intersection: def __init__(self, length, prob, keepalive, wait_weight): self.NSRoad = Road(length,prob) self.EWRoad = Road(length,prob) self.keepalive = keepalive self.total_reward = 0 self.length = length self.prob = prob self.end = False self.wait_weight = wait_weight def getState(self): temp = np.array([np.array(self.NSRoad.binaryRepresentation()), np.array(self.EWRoad.binaryRepresentation())]) return temp def newInstance(self): self.NSRoad = Road(self.length, self.prob) self.EWRoad = Road(self.length, self.prob) self.end = False self.total_reward = 0 def getReward(self): return self.total_reward def gameEnd(self): return self.end def step(self,NS_action, EW_action): NSoutput = self.NSRoad.step(NS_action) EWoutput = self.EWRoad.step(EW_action) step_reward = 0 if (NSoutput[1][0] == 1) and (EWoutput[1][0] == 1): self.NSRoad.crash() self.EWRoad.crash() self.total_reward -= 100 self.end = True return -100 if (NSoutput[0][0] == 1): step_reward += 15 if (EWoutput[0][0] == 1): step_reward += 15 wait_penalty = self.wait_weight * (self.NSRoad.totalWait() + self.EWRoad.totalWait()) step_reward += (self.keepalive - wait_penalty) self.total_reward += step_reward return step_reward
def create_roads(): print("[STARTING....] creating roads") for i in range(0, 4): rd = Road(i) ROADS.append(rd) print("[CREATING] ==> creating road {}".format(rd)) for pos in ['left', 'right']: lt = Lights() lt.start_traffic() rd.set_light(pos, lt) print(colored("[ADDED]", "green"), f" traffic light to {rd}-{pos}") print(colored('[DONE]', 'green'), " Roads created")
def initialize_2(): global time, agents, lightAgents, envir, agents1 time = 0 road_1 = Road(0, 10, 10, 10, 'west') car_1 = Car(0, 0, road_1) agents1 = [car_1]
def load_map(path: Path): map_df = pd.read_csv(path, usecols=['the_geom']) print(f"Read dataframe of shape {map_df.shape}") roads = [] for road in map_df['the_geom']: roads.append(Road.load_from_linestring(road)) return Map(roads)
def __init__(self,npc,name,location): #self.shop = shop self.npc = npc self.name = name self.location = location self.roads = [Road("0 rd",[0,0],[0,4]),Road("1 rd",[0,1],[-1,1]), Road("2 rd",[-1,1],[-1,2]),Road("3 rd",[0,3],[-1,2]), Road("4 rd",[-1,2],[0,3]),Road("5 rd",[0,2],[1,2]), Road("6 rd",[0,4],[1,4]),Road("7 rd",[1,4],[1,3])]
def makeVertexStartRoad(self, event): if event.button() == Qt.RightButton: point = Point(event.x(), event.y()) if not self.vertices or self.mindistance(point) > 50: self.vertices.append(Vertex.newVertex(event.x(), event.y(), self.net)) point = Point(event.x(), event.y()) if event.button() == Qt.LeftButton and self.vertices and self.mindistance(point) <= 20: v = self.closestvertex(point) self.newroad = Road(v, self.net, self.n, self.isOneSided) self.basepoint = Point(v.x(), v.y()) self.pointList.append(self.basepoint) self.signal.switch.emit()
def populate_edges(self, single_row): """ From each row of an Excel sheet Connection,it creates object of Road and Using existing nodes it creates the edges and hence the graph is generated Args: :param single_row: represents one row of the sheet Connection of an excel file """ road = Road(single_row[2], single_row[3], single_row[4], single_row[5]) self.__G.add_edge(self.__node_by_id[single_row[0]], self.__node_by_id[single_row[1]], link=road._length, name=road._name, direction=road._direction) if single_row[2] == 2: direction_op = single_row[3][1] + single_row[3][0] road_1 = Road(single_row[2], direction_op, single_row[4], single_row[5]) self.__G.add_edge(self.__node_by_id[single_row[1]], self.__node_by_id[single_row[0]], link=road_1._length, name=road_1._name, direction=road_1._direction)
def __init__(self, ): super(RoadLSTM, self).__init__() # self.attr_net = Attr() self.Road_net = Road() # self.process_Roads_hiddens = nn.Linear(64, 32) self.Road_lstm = nn.LSTM( input_size = 32, \ hidden_size = 32, \ num_layers = 1, \ batch_first = True, \ bidirectional = False, \ dropout = 0 )
def prepareMap(self, mazeArray): x, y = 0, 0 spriteWall = pygame.image.load("img/wall.png") spriteRoad = pygame.image.load("img/ground.png") for row in mazeArray: for cell in row: if cell: self.walls.append(Wall(y, x, spriteWall)) self.roads.append(Road(y, x, spriteRoad)) y += config.SIZE_OF_WALL x += config.SIZE_OF_WALL y = 0
def __init__(self, params): """Initializes new model with provided set of parameters. :param params: Model parameters. :type params: dictionary""" self.time = timedelta() self._cars = [] self._enterQueue = [] self._lights = [] self._road = Road() self._lastCarGenerationTime = timedelta() self.params = params self._loggerName = 'kts46.roadModel' self._logger = logging.getLogger(self._loggerName) self._lastCarId = -1
def build(self, display): path = "" while self.height + self.path_height < self.Dinfo.current_h: r_num = random.randint(0, 2) if r_num <= 1: path = Road(display, self.path_height + self.height, self.player, self.path_height) else: path = River(display, self.path_height + self.height, self.player, self.path_height) if self.height + path.height + self.path_height < self.Dinfo.current_h: self.paths.append(path) self.height = path.y + path.height else: break
def __init__(self, ): super(RoadLSTM, self).__init__() # self.attr_net = Attr() self.Road_net = Road() # self.process_Roads_hiddens = nn.Linear(64, 32) self.Road_lstm = nn.LSTM( input_size = 32, \ hidden_size = 32, \ num_layers = 1, \ batch_first = True, \ bidirectional = False, \ dropout = 0 ) nn.init.uniform_(self.Road_lstm.state_dict()['weight_hh_l0'], a=-0.05, b=0.05)
def updateDynamics(self, env = Env()): road = Road() road = env.road time = env.time sampleTime = Env.CONST_sampleTime if(heading2 == -999.0): heading = heading1 = heading2 = math.atan2(h.z, h.x) yout[1] = y[1] = car_heading = heading yout[2] = y[2] = 0.0 yout[3] = y[3] = 0.0 yout[4] = y[4] = car_ke = 50000 # 0.0; # kinetic energy > 0, otherwise unstable at start yout[5] = y[5] = p.x yout[6] = y[6] = p.z if(car_ke > 0.0): car_speed = car.sqrt(2.0 * car_ke/ms) else: car_speed = 0.0 car_steer = steerAngle car_accel_pedal = accelerator car_brake_pedal = brake
def play(): n = int(input("Number of cars: ")) ds = float(input("Crossroad length: ")) dt = float(input("Yellow light time: ")) road = Road(ds,dt) prev = 0 for i in range(n): x0 = 0 v = float(input("Initial velocity: ")) maxv = float(input("Maximum velocity: ")) ap = float(input("Positive acceleration: ")) an = float(input("Negative acceleration: ")) if i == 0: x0 = prev + float(input("Initial distance: ")) else: x0 = prev + float(input("Distance: from previous car")) prev = x0 color = input("Color of the car: ") road.add_car(Car(x0,v,an,ap,maxv,color)) road.test_for_stop() road.plot()
def generato_roado(self, current, connected, distances): if len(distances) == 0 and len(connected) > 0: return True connected.append(current) shortest = None for c2 in self.cities: if (current is not c2) and (c2 not in connected): distances.append([current, c2, dist(current.pos, c2.pos)]) for distance in distances: if distance[1] not in connected: if shortest is None: shortest = distance elif distance[2] < shortest[2]: shortest = distance else: distances.remove(distance) if shortest is None: return True self.roads.append(Road(shortest[0].pos, shortest[1].pos)) if self.generato_roado(shortest[1], connected, distances): return True
def _create_road(self, room1_info, room1, room2_info, room2): road = Road(room1, room1_info, room2, room2_info) if not road.can_connect: return False self.roads.append(road) return True
c1_x, c1_y, c2_x, c2_y = city1.x_pos, city1.y_pos, city2.x_pos, city2.y_pos return int( math.sqrt(math.pow(c2_x - c1_x, 2) + math.pow(c2_y - c1_y, 2)) * 1.4) with open('data/cities.csv') as csv_file: buffer = csv.reader(csv_file, delimiter=',') for line in buffer: graph.cities[line[0]] = City(line[0], int(line[1]), int(line[2])) with open('data/roads.csv') as csv_file: buffer = csv.reader(csv_file, delimiter=',') for line in buffer: city1, city2 = line[0], line[1] cost = calculate_distance(graph.cities[city1], graph.cities[city2]) road = Road(graph.cities[city1], graph.cities[city2], cost) graph.roads.append(road) graph.cities[city1].add_road(road) graph.cities[city2].add_road(road) root = Tk() frame = Frame(root, width="1492", height="900") frame.grid(row=0, column=0) root.title("Navigation on Turkey Map") algorithm_font = tkfont.Font(family='Helvetica', size=30, weight="bold") Label(frame, text="Navigation on Turkey Map", font=algorithm_font).grid(row=0, column=0) map_img = PhotoImage(file='data/turkey-map.png')
def init_window(self): OBSTACLE_SIZE = 5 ROAD1_START = 300 ROAD_DISTANCE = 100 CAR_WIDTH = 10 CAR_START = ROAD1_START + ROAD_DISTANCE - 50 CAR_LENGTH = 5 Y_SIZE = 700 self.master.title("Autonomous Vehicle") # allow widget to take the full space of the root window self.pack(fill=BOTH, expand=1) # canvas widget canvas = Canvas(self) # create a button #quitButton = Button(self, text="Quit", command=self.client_exit) # place button on the window #quitButton.place(x=0, y=0) # create a ractangle (placeholder for car) # parameters for rectangle: (x0, y0, x1, y1, option, ...) #canvas.create_rectangle(400, 600, 430, 660, outline="gray", fill="gray", width=2) #canvas.pack(fill=BOTH, expand=1) # d = [ [None for y in range(2) ] for x in range(2)] iterations = 10000 iteration = 1 max_fit = 0 top_fit = 0 for its in range(iterations): self.grid = [] self.cars = [] self.obstacles = [] iteration_lbl = Label(self, text="Iteration: " + str(iteration), font=("Helvitica", 16), fg="red") iteration_lbl.place(x=0, y=30) iteration += 1 max_fit_lbl = Label(self, text="Max Fitness: " + str(max_fit), font=("Helvitica", 16), fg="red") max_fit_lbl.place(x=0, y=60) #top_fit_lbl = Label(self, text="Top Fitness: " + str(top_fit), font=("Helvitica", 16), fg="red") #top_fit_lbl.place(x=0, y=90) road = Road(canvas, ROAD1_START, 0, ROAD_DISTANCE, Y_SIZE) road1_array, road2_array = road.line_coords() road1_array = road.get_x1_coords() x = ROAD1_START for i in range(10): car = Car(canvas, x, 0, CAR_WIDTH, CAR_LENGTH, str(i)) self.cars.append(car) x += 10 #obs_pos = obstacle1.obstacle_coords() for i in range(len(road1_array)): roadx = road1_array[i] self.grid.append(roadx) for i in range(70): if random.randint(0, 10) == 0: self.obstacles.append(random.randint(0, 9)) else: self.obstacles.append(-1) for i in range(70): if self.obstacles[i] != -1: Obstacle(canvas, OBSTACLE_SIZE, i * 10, self.grid[i] + self.obstacles[i] * 10, road1_array, ROAD_DISTANCE) #obstacle1.get_x_y_coords(road1_array, road2_array) # done = car.car_update(road1_array, road2_array, obs_pos, ROAD_DISTANCE) y = 0 crashed = [False] * 10 while not pop.done(): for j in range(len(self.cars)): if not pop.crashed[j]: if j == 5: print("Car " + str(j) + " position: " + str(self.cars[j].x0)) print("position: " + str(pop.car[j])) print("obs: " + str(self.obstacles[y])) move = pop.get_car(j).get_move(int(self.grid[y] / 10), pop.car[j], self.obstacles[y]) self.cars[j].car_update(road1_array, road2_array, ROAD_DISTANCE, move) if y == 0: pop.make_move(int(self.grid[y] / 10), self.obstacles[y], 0) #print(self.grid[y]) else: pop.make_move(int(self.grid[y] / 10), self.obstacles[y], int((self.grid[y - 1] - self.grid[y]) / 10)) #print(self.grid[y]) if y == 69: print("new road") new_road_start = road1_array[len(road1_array) - 1] print("last road pos: " + str(road1_array[len(road1_array) - 1])) new_x_coords = [] for i in range(len(self.cars)): new_x_coords.append(self.cars[i].x0) canvas.delete("all") #canvas.after(1000, canvas.delete, road) #canvas.delete(road) canvas.update() # redraw road road = Road(canvas, new_road_start, 0, ROAD_DISTANCE, Y_SIZE) self.cars = [] # redraw cars for i in range(len(new_x_coords)): car = Car(canvas, new_x_coords[i], 0, CAR_WIDTH, CAR_LENGTH, str(i)) self.cars.append(car) road1_array, road2_array = road.line_coords() road1_array = road.get_x1_coords() #obs_pos = obstacle1.obstacle_coords() self.grid = [] self.obstacles = [] for i in range(len(road1_array)): roadx = road1_array[i] self.grid.append(roadx) for i in range(140): if random.randint(0, 10) == 0: self.obstacles.append(random.randint(0, 9)) else: self.obstacles.append(-1) for i in range(70): if self.obstacles[i] != -1: Obstacle(canvas, OBSTACLE_SIZE, i * 10, self.grid[i] + self.obstacles[i] * 10, road1_array, ROAD_DISTANCE) #self.cars[j].car_update(road1_array, road2_array, ROAD_DISTANCE, move) y = 1 y += 1 print(pop.fit) canvas.delete("all") #canvas.after(1000, canvas.delete, road) #canvas.delete(road) canvas.update() pop.rank_fitness() top_fit = pop.fit[0][1] if top_fit > max_fit: max_fit = top_fit pop.breed(10, 95, 1)
from Road import Road from LaneSprite import LaneSprite import Colors, random, sys, pygame, ModelData as data, GraphicResources as gr ########### App Variables ########### appStates = [ 'Nagel-Schreckenberg Model', 'Nagel-Schreckenberg Model (Running)', 'Nagel-Schreckenberg Model (Paused)' ] road = Road() clock = pygame.time.Clock() ##################################### ########### Display Data ########### pygame.display.init() resolution = pygame.display.Info() size = width, height = resolution.current_w, resolution.current_h pygame.display.set_mode((width, int((height * 90) / 100))) pygame.display.set_caption(appStates[data.appState]) screen = pygame.display.set_mode(size) pygame.font.init() myfont = pygame.font.SysFont('Arial', 12) tableFont = pygame.font.SysFont('Arial', 15) #################################### ###### Loading Graphic Resources ###### gr.backgroundImg = pygame.transform.scale(gr.backgroundImg, [width, height]) gr.chargeCarImages() ####################################### ########## CONTROLS ##########
class Model(object): "Defines a model that can simulate road traffic." defaultParams = {'inputRate': 1200, 'safeDistance': 20, 'safeDistanceRear': 10, 'trafficLightStopDistance': 5, "accelerationLimit": 2.0, # m / s^2 for (13.5 s to 100 kmph) "brakingLimit": 6.5, # m / s^2 (like 21 m from 60 kmph) "comfortBrakingLimit": 4.5, # m / s^2 "driverReactionTime": 0.8, # s "minimalDistance": 3, # m "speed": [10, 20], # m/s "lineChangingDelay": 1.0 # m/s } def __init__(self, params): """Initializes new model with provided set of parameters. :param params: Model parameters. :type params: dictionary""" self.time = timedelta() self._cars = [] self._enterQueue = [] self._lights = [] self._road = Road() self._lastCarGenerationTime = timedelta() self.params = params self._loggerName = 'kts46.roadModel' self._logger = logging.getLogger(self._loggerName) self._lastCarId = -1 def run_step(self, milliseconds): """Performs one step of simulation. :param milliseconds: length of step in milliseconds. :type milliseconds: int""" stopDistance = self.params['safeDistance'] timeStep = timedelta(milliseconds=milliseconds) newTime = self.time + timeStep # Time after step is performed. for light in self._lights: if newTime > light.getNextSwitchTime(): light.switch(newTime) toRemove = [ ] for car in self._cars: if car.state != Car.DELETED: car.prepareMove(timeStep) else: toRemove.append(car) for car in toRemove: self._cars.remove(car) for car in self._cars: car.finishMove() # Generate new car. # It is always added to the queue and if there is enough place then # it will be instantly added to the road. carsToAdd, newLastCarTime = self.howManyCarsToAdd(newTime) self.addCars(carsToAdd) self._lastCarGenerationTime = newLastCarTime self.addCarsFromQueueToRoad() # Update time. self.time = newTime def addCarsFromQueueToRoad(self): "Add cars from entering queue to road." # If there is a car in the queue, then send it. # Try to add cars while there was at least one succesfull added. addCar = True while len(self._enterQueue) > 0 and addCar: # Start with generated line and if it is busy try others. addCar = False if self.canAddCar(self._enterQueue[0].line): addCar = True else: # This algorithms favorites first lines. That is considered # logical in most cases. for i in range(0, self._road.lines): if self.canAddCar(i): self._enterQueue[0].line = i addCar = True break if addCar: self._addCar(self._enterQueue[0]) del self._enterQueue[0] def addCars(self, amount): """Add cars to entering queue. :param amount: Amount of cars to add to queue. :type amount: int""" speedMultiplier = self.params['speed'][1] - self.params['speed'][0] speedAdder = self.params['speed'][0] for i in xrange(amount): speed = math.floor(random.random() * speedMultiplier) + speedAdder self._lastCarId += 1 line = math.floor(random.random() * self._road.lines) newCar = Car(model=self, road=self._road, id=self._lastCarId, speed=speed, line=line) self._logger.debug('Created car: [speed: %f].', speed) self._enterQueue.append(newCar) def howManyCarsToAdd(self, newTime): "Define how many cars can be added to the model." newCarGenRate = timedelta(seconds=3600/self.params['inputRate']) lastCarTime = self._lastCarGenerationTime carsToGenerate = 0 while lastCarTime <= newTime: carsToGenerate += 1 lastCarTime += newCarGenRate return (carsToGenerate, lastCarTime) def getNearestTrafficLight(self, position): "Get nearest traffic light to specified position in forward destination." return self.getNearestObjectInArray(self._lights, position) def getNearestCar(self, position, line=0): """Get nearest car to specified position in forward destination. If there is no leading car, then ``None`` will be returned.""" return self.getNearestObjectInArray(self._cars, position, line) def getNearestObjectInArray(self, array, position, line=0): "Get nearest object in array to specified position in forward destination." position += 0.1 current = None current_pos = -1.0 # just to make sure :) for i in array: # Check if it is in our line and skip it if not. # Objects that has not line attribute affect all lines, # like traffic lights. if hasattr(i, "line") and i.line != line: continue # Deleted cars already doesn't exists. if hasattr(i, "state") and i.state == Car.DELETED: continue pos = i.position #if hasattr(i, "length"): # pos -= i.length # >= is very important so car won't try to go through another car. if pos >= position and ((current is None) or current_pos > pos): current = i current_pos = pos return current def getFollowingCar(self, position, line=0): """Get nearest following car to specified position in backward destination. If there is no following car, then ``None`` will be returned.""" return self.getFollowingObjectInArray(self._cars, position, line) def getFollowingObjectInArray(self, array, position, line=0): "Get nearest object in array to specified position in backward destination." current = None current_pos = -1.0 # just to make sure :) for i in array: # Check if it is in our line and skip it if not. # Objects that has not line attribute affect all lines, # like traffic lights. if hasattr(i, "line") and i.line != line: continue # Deleted cars already doesn't exists. if hasattr(i, "state") and i.state == Car.DELETED: continue pos = i.position if pos <= position and ((current is None) or current_pos < pos): current = i current_pos = pos return current def canAddCar(self, line=0): "Defines whether car can be added to specified line." lastCar = self.getNearestCar(-100.0, line) # Detect cars which are comming on the road. return lastCar is None or lastCar.position - lastCar.length > self.params['safeDistance'] def _addCar(self, car): "Add car to the model, but not to the road." self._cars.append(car) car.state = Car.ADDED def getStateData(self): """Returns object data that represents current state of a model.""" data = {} # Traffic lights lights = {} for light in self._lights: lights[light.id] = light.getStateData() data['trafficLights'] = lights # Cars cars = {} for car in self._cars: cars[car.id] = car.getStateData() cars[car.id].update(car.getDescriptionData()) data['cars'] = cars # Enter queue enterQueue = [] for car in self._enterQueue: enterQueue.append(car.getStateData()) enterQueue[-1].update(car.getDescriptionData()) data['enterQueue'] = enterQueue # Fields data['time'] = kts46.utils.timedelta2str(self.time) data['lastCarGenerationTime'] = kts46.utils.timedelta2str(self._lastCarGenerationTime) data['lastCarId'] = self._lastCarId # Result. return data def getDescriptionData(self): "Gets dictionary describing model." data = {} data['modelParameters'] = self.params lights = {} for light in self._lights: lights[light.id] = light.getDescriptionData() data['trafficLights'] = lights if self._road is not None: data['road'] = self._road.getDescriptionData() return data def load(self, description, state=None): "Loads object from JSON data." self.params = description['modelParameters'] self._road.load(description['road']) for lightId, lightData in description['trafficLights'].iteritems(): light = SimpleSemaphore(id=lightId) lState = {} if state is not None: lState = state['trafficLights'][lightId] light.load(lightData, lState) self._lights.append(light) if state is not None: for carData in state['cars'].itervalues(): c = Car(model=self, road=self._road) c.load(carData, carData) self._cars.append(c) for carData in state['enterQueue']: c = Car(model=self, road=self._road) c.load(carData, carData) self._enterQueue.append(c) # Fields self.time = kts46.utils.str2timedelta(state['time']) self._lastCarGenerationTime = kts46.utils.str2timedelta(state['lastCarGenerationTime']) self._lastCarId = state['lastCarId']
lanes = [] for lane in range(3): lanes.append([]) for pos in drange(0, 10000, 50): if pos == 0: v = v0 else: v = v0 + random.uniform(-10, 10) p = pos + random.uniform(0, 0) c = Car(pos=-1 * p, vel=v, c="blue") lanes[lane].append(c) lanes[0][0].velocity = 33.0 lanes[1][0].velocity = 33.0 lanes[2][0].velocity = 33.0 road = Road(lanes) data, t = rk4(IDM, delT, iterations, road, 0.0) ''' vs = [] for iteration in data[0]: velocities = [] for car in iteration: velocities.append(car.velocity) vs.append(sum(velocities)/float(len(iteration))) ax1.plot(t, vs) plt.show() ''' for carNum in range(len(data[0][0])): ps = [el[carNum].position for el in data[0]] ax1.plot(t, ps)
class Intersection: def __init__(self, length, prob, keepalive, wait_weight): self.NSRoad = Road(length, prob) self.EWRoad = Road(length, prob) self.NSwait = 0 self.EWwait = 0 self.passedCars = 0 self.keepalive = keepalive self.total_reward = 0 self.length = length self.prob = prob self.end = False self.wait_weight = wait_weight self.numSteps = 0 def getState(self): temp = np.array([ self.NSRoad.binaryRepresentation(), self.NSRoad.carRepresentation(), self.EWRoad.binaryRepresentation(), self.EWRoad.carRepresentation() ]) return temp def getBinary(self): state = [] temp = self.NSRoad.binaryRepresentation() for i in range(0, 4): state.append(temp[i]) temp = self.EWRoad.binaryRepresentation() for i in range(0, 4): state.append(temp[i]) state.append((self.NSwait + self.EWwait)) return np.array(state) def newInstance(self): self.NSRoad = Road(self.length, self.prob) self.EWRoad = Road(self.length, self.prob) self.end = False self.passedCars = 0 self.total_reward = 0 def getReward(self): return self.total_reward def gameEnd(self): return self.end def gameWait(self): print("Wait NS: " + str(self.NSRoad.totalWait())) print("Wait EW: " + str(self.EWRoad.totalWait())) def step(self, NS_action, EW_action): if (NS_action == 1): self.NSwait += 1 else: self.NSwait = 0 if (EW_action == 1): self.EWwait += 1 else: self.EWwait = 0 #self.numSteps += 1 NSoutput = self.NSRoad.step(NS_action) EWoutput = self.EWRoad.step(EW_action) step_reward = 0 if ((NSoutput[1][0] == 1) and (EWoutput[1][0] == 1)) or ( (self.NSwait + self.EWwait) > 10) or (self.total_reward < -200): self.NSRoad.crash() self.EWRoad.crash() self.total_reward -= 100 self.end = True return -100 if (NSoutput[0][0] == 1): step_reward += 20 self.passedCars += 1 if (EWoutput[0][0] == 1): step_reward += 20 self.passedCars += 1 wait_penalty = self.wait_weight * (self.NSwait + self.EWwait) step_reward += (self.keepalive - wait_penalty) self.total_reward += step_reward return step_reward
def newInstance(self): self.NSRoad = Road(self.length, self.prob) self.EWRoad = Road(self.length, self.prob) self.end = False self.passedCars = 0 self.total_reward = 0
def test(): car1 = Car(30,50,3,3,100,"blue") car2 = Car(20,80,3,3,100,"green") road = Road(1,2) road.add_car(car1) road.add_car(car2) road.test_for_stop() road.plot() car1 = Car(30,40,1.5,2.5,100,"blue") road = Road(1,2) road.add_car(car1) road.test_for_stop() road.plot()
phyCl = p.connect(p.GUI) p.setAdditionalSearchPath(pybullet_data.getDataPath()) plane = p.loadURDF("plane.urdf") # load the plane p.setGravity(0, 0, -10) # set gravity p.setRealTimeSimulation(1) p.resetDebugVisualizerCamera(5.18, 88, -449, [0, 0, 13]) consts_obj = Const() # Const instance to call the class print("ROAD HAS: ", consts_obj.NUMBER_OF_POINTS(), " POINTS!") #print(Const.NUMBER_OF_POINTS()) #p.configureDebugVisualizer(p.COV_ENABLE_WIREFRAME, 1) road = Road() road.create_road() robot = Goodbot( "goodbot.urdf", road.get_road_points()[len(road.get_road_points()) * 3 // 4].get_road_point_position()) p.setRealTimeSimulation(1) velocity = 0 rarr = p.B3G_RIGHT_ARROW larr = p.B3G_LEFT_ARROW uarr = p.B3G_UP_ARROW darr = p.B3G_DOWN_ARROW
def __init__(self, w, h, seed, size): self.tiles = [] self.width = w self.height = h self.seed = seed self.size = size self.cities = [] self.roads = [] #Confine variabels if size < 1: size = 1 elif size > 10: size = 10 self.dimensions = w if w < h: self.dimensions = h #Generate map p = pGrid(size, self.dimensions, self.seed) #Find extremedies i,j = np.unravel_index(p.argmin(), p.shape) min_val = p[i,j] i,j = np.unravel_index(p.argmax(), p.shape) max_val = p[i,j] size_val = max_val if size_val < abs(min_val): size_val = abs(min_val) for x in range(w): self.tiles.append([]) for y in range(h): tile = tanh(p[x][y]/(0.90*size_val)) * 0.5 + 0.5 if tile < 0.2: tile_info = (0, (13 - tile * 54, 61 - tile * 57, 120 - tile * 61), 0.2) #Water elif tile < 0.22: tile_info = (1, (246, 220, 55), 0.75) #Beach elif tile < 0.65: tile_info = (2, (146, 203, 54), 1.25) #Grassland elif tile < 0.7: tile_info = (3, (107, 164, 15), 1) #Highlands elif tile < 0.8: tile_info = (4, (-45 * (tile-0.7)*10 + 140, -45 * (tile-0.7)*10 + 140, -45 * (tile-0.7)*10 + 140), 0.6) #Mountain else: tile_info = (5, (55 * (tile-0.8)*5 + 200, 55 * (tile-0.8)*5 + 200, 55 * (tile-0.8)*5 + 200), 0.45) #Mountain_top_snow self.tiles[x].append(tile_info) # City generation for i in range(100): pos = (randint(8,w-8), randint(8,h-8)) if self.tiles[pos[0]][pos[1]][0] == 2: # Checks if city bouandaries are okay if self.tiles[pos[0]][pos[1]-4][0] == self.tiles[pos[0]-4][pos[1]][0] == self.tiles[pos[0]+4][pos[1]][0] == self.tiles[pos[0]][pos[1]+4][0] == 2: good_pos = True for city in self.cities: if dist(pos, city.pos) < 25: good_pos = False if good_pos: self.cities.append(City(pos)) # Road generation dists = [] for c1 in self.cities: # Generating list of all possible city connections and the length thereof for c2 in self.cities: # if c1 is not c2: # dists.append((c1, c2, dist(c1.pos, c2.pos))) # Create touple of 2 cities and distance: (c1, c2, float: 'distance') and adds them to 'dists' list connections = [[]] # Connected cites unfound = self.cities.copy() # Unconnected cities for un in unfound: s_dist = shortets_dist(dists) if self.uninterrupted_path(s_dist): connections[-1].append(s_dist) # Append to new connection to connections unfound.remove(s_dist[0]) # and unfound.remove(s_dist[1]) # Remove now found cities break else: unfound.pop(unfound.index(un)) while len(unfound) != 0: #Keeps going until there are no more unfound citites (all cities are found) # Finds the shortest connection which has both a connection to 'connected' and to 'unfound' insuring a correct connection cons = [] for con in connections[-1]: for dis in dists: if (con[0] in dis[:2] or con[1] in dis[:2]) and (dis[0] in unfound or dis[1] in unfound): if self.uninterrupted_path(dis): # Check for landscape violation (if the road crosses something besides Grass- or Highlands) cons.append(dis) s_dist = shortets_dist(cons) if s_dist is not None: connections[-1].append(s_dist) # Add new connection i = 0 # Delete city from unfound if s_dist[1] in unfound: # i = 1 # unfound.remove(s_dist[i]) # elif len(unfound) > 1: cons = [] for dis in dists: if dis[0] in unfound and dis[1] in unfound: if self.uninterrupted_path(dis): cons.append(dis) s_dist = shortets_dist(cons) if s_dist is not None: connections[-1].append(s_dist) # Add to new connection to connections unfound.remove(s_dist[0]) # and unfound.remove(s_dist[1]) # Remove now found cities else: unfound[:] = [] else: break for con in connections: # Create road objects and add to self.roads for c in con: # self.roads.append(Road(c[0], c[1], c[2])) # self.cities[self.cities.index(c[0])].roads.append(c[1]) # Give cities connected cities as "roads" self.cities[self.cities.index(c[1])].roads.append(c[0]) #
# The capital letters are a convention for a constant. #---------------------------------------------------------------------------------------------------- # Add comments to say what these are DEFAULT_SPEEDS = {'Freeway': 65, 'Arterial': 35, 'Collector': 30, 'Local': 20} # FILES--change as needed INFILE = "C:/temp/blueprints.txt" OUTFILE = "C:/temp/finished_road.txt" #---------------------------------------------------------------------------------------------------- # Main function call. #---------------------------------------------------------------------------------------------------- if __name__ == "__main__": # this lets you specify a command line argument. The first argument is the # name of the script. LANES is capital because it won't change during the script. if len(sys.argv) < 2: print('Enter the number of lanes: python build_road.py 2') sys.exit(2) LANES = int(sys.argv[1]) # do some stuff limestone = Road(LANES) print('Repaved at: ', limestone.repave_date) time.sleep(3) limestone.repave() print('Repaved at: ', limestone.repave_date) # all done print('Run complete! Woohoo!')