def __init__(self, _num_of_roads, size_of_road, size_of_bridge):
     if _num_of_roads < 4:
         self.num_of_roads = 4
     if _num_of_roads % 2 == 1:
         self.num_of_roads += 1
     else:
         self.num_of_roads = _num_of_roads
     self.roads = [None] * self.num_of_roads
     # self.roads = [Road(size_of_road)] * self.num_of_roads
     for i in range(self.num_of_roads):
         self.roads[i] = Road(size_of_road)
     self.bridge = Road(size_of_bridge)
     self.state = []
Exemple #2
0
    def load_sections(self, road_network):
        self.cursor.execute('SELECT * FROM get_section();')
        for (id, name, number_lanes, speed_limit, capacity, from_node_id,
             to_node_id, length) in self.cursor.fetchall():

            if id in road_network.sections:
                raise Error("section id=%d already exists" % id)
            if from_node_id not in road_network.nodes:
                raise Error("section id=%d unknown from-node=%d" %
                            (id, from_node_id))
            if to_node_id not in road_network.nodes:
                raise Error("section id=%d unknown to-node=%d" %
                            (id, to_node_id))

            road_name = name.title()
            if road_name not in road_network.roads:
                road_network.roads[road_name] = Road(road_name)
            road = road_network.roads[road_name]

            from_node = road_network.nodes[from_node_id]
            to_node = road_network.nodes[to_node_id]
            section = Section(id, road, number_lanes, speed_limit, capacity,
                              from_node, to_node, length)
            from_node.add_from_section(section)
            to_node.add_to_section(section)
            road_network.sections[id] = section
            road.sections.append(section)
Exemple #3
0
def initialize_2():
    global time, lightAgents, envir, cars

    time = 0
    road_1 = Road(0, 10, 10)
    car_1 = Car(0, 0)
    cars = []
Exemple #4
0
 def get_string(self):
     self.new_string = input("Type the string to validate: ")
     # self.create_error_character()
     self.reviewed = []
     current_state = self.initial_state
     self.roads = [Road([current_state], True)]
     self.make_epsilon_transitions()
     for symbol in self.new_string:
         # self.make_epsilon_transitions()
         self.change_road_status()
         for road in self.roads:
             if road.check_now == True:
                 aux_state = []
                 for transition in self.transitions_objects:
                     aux_state.append(transition.get_next_state(road.way[-1], symbol))
                 aux_state = [state for state in aux_state if state != "error"]
                 if len(aux_state) > 0:
                     if ( len(aux_state) > 1 ):
                         self.create_new_roads(road, aux_state)
                         road.add_to_road(aux_state[0])
                     else:
                         road.add_to_road(aux_state[0])
                 else:
                     road.add_error(road.way[-1], symbol)
         self.make_epsilon_transitions()
def parse_map(filename):
    # initialize location dictionary {ID -> Location} and road dictionary {ID -> list[Road]}
    locationDict = {}
    roadDict = {}

    # parse file
    with open(filename, "r") as file:
        for line in file:
            # remove \n and split line by delimiter
            line = line.rstrip()
            splitLine = line.split("|")

            # create new Location instances for "location" lines and add them to locationDict
            if splitLine[0] == "location":
                newLocation = Location(splitLine[1], splitLine[2],
                                       splitLine[3])
                locationDict[splitLine[1]] = newLocation

            # create new Road instances for "road" lines and add them to roadDict
            elif splitLine[0] == "road":
                newRoad = Road(splitLine[4], splitLine[3], splitLine[1],
                               splitLine[2])

                if splitLine[1] in roadDict.keys():
                    roadDict[splitLine[1]] += [newRoad]
                else:
                    roadDict[splitLine[1]] = [newRoad]

                if splitLine[2] in roadDict.keys():
                    roadDict[splitLine[2]] += [newRoad]
                else:
                    roadDict[splitLine[2]] = [newRoad]

        file.close()
    return locationDict, roadDict
def test_update():
    r = Road(1, 2, 3, [Car()])
    assert np.all(r.cells == [1, 0, 0])
    r.update()
    assert np.all(r.cells == [0, 1, 0])
    r.update()
    assert np.all(r.cells == [0, 0, 1])
Exemple #7
0
def run_simulation(VISUALIZE=True):
    road = Road(SPEED_LIMIT, TRAFFIC_DENSITY, LANE_SPEEDS,
                AMOUNT_OF_ROAD_VISIBLE)
    road.populate_traffic()
    ego_config = {
        'speed_limit': SPEED_LIMIT,
        'num_lanes': len(LANE_SPEEDS),
        'goal': GOAL,
        'max_acceleration': MAX_ACCEL,
    }
    # Ego begins travelling at lane #2.
    road.add_ego(2, 0, ego_config)
    timestep = 0
    while road.get_ego().s <= GOAL[0]:
        timestep += 1
        if timestep > 150:  # simulation time limit
            if VISUALIZE:
                print("Taking too long to reach goal. Go faster!")
            break

        road.advance()
        if VISUALIZE:
            print(road)
            time.sleep(float(1.0) / FRAMES_PER_SECOND)

    # Completed to the goal distance
    ego = road.get_ego()
    if VISUALIZE:
        if ego.lane == GOAL[1]:
            print("You got to the goal in %d seconds!" % timestep)
        else:
            print("You missed the goal. "
                  "You are in lane %d instead of %d." % (ego.lane, GOAL[1]))
    return timestep, ego.lane
Exemple #8
0
def basicRoad():
    r = Road()
    r.addSegment(Segment(100, theGear=Gear.DIRECT))
    r.addSegment(Segment(50, theGear=Gear.TURN))
    r.addSegment(Segment(100, theGear=Gear.DIRECT))
    r.addSegment(Segment(50, theGear=Gear.TURN))
    return r
    def set_roads(self, G, node_dict):
        
        """
        Method: set_roads

        Method Arguments:
        * G - The graph of a real section of the world that will be produced
              from using the osmnx package and the lat and lon provided by the
              user input.

        * node_dict - The node dictionary that will be used to show which roads
                        are connected to each other.

        Output:
        * A dictionary of the edges created will be returned, where each edge id
          is their key.
        """ 
        
        edge_dict = {}
        id = 0
        for e in G.edges(data=True):
            start = node_dict[e[0]]
            destination = node_dict[e[1]]
            length = int(e[2]['length']) 
            #name = e[2]['name']
            edge_to_insert = Road(id, start, destination, length)
            if id in edge_dict: 
                print("duplicate edge")
            edge_dict[id] = edge_to_insert
            id+=1
        #removed bad edge
        return edge_dict
 def setUp(self):
     """
     Compute following code before each test.
     """
     self.road = Road(road_length = 3.0,density_max = 120.0,free_v = 50.0,mean_time_gap =0.6,source=0.8)
     self.road.make_cells()
     self.cell = Cell(self.road)
def main():
    road = Road(number_of_cars=30)
    number_of_runs = 100
    seconds_in_run = 60

    road.place_cars()
    speed_limit_list = []
    positions_list = []
    speeds_list = []
    mean_speeds = []
    st_devs = []

    for _ in range(number_of_runs):
        speeds, positions = road.simulate_n_seconds(seconds_in_run)

        mean = np.mean(speeds)
        stdv = np.std(speeds)
        speed_limit_list.append(mean + stdv)
        mean_speeds.append(mean)
        st_devs.append(stdv)

        if _ in {0, 9, 34, 74, 99}:
            positions_list.append(positions[:])
            speeds_list.append(speeds)

    return (int(np.mean(speed_limit_list)), positions_list, speeds_list,
            mean_speeds, st_devs)
def run_simulation(VISUALIZE=True):
    road = Road(SPEED_LIMIT, TRAFFIC_DENSITY, LANE_SPEEDS, AMOUNT_OF_ROAD_VISIBLE)
    road.populate_traffic()
    ego_config = {
        'speed_limit': SPEED_LIMIT,
        'num_lanes': len(LANE_SPEEDS),
        'goal': GOAL,
        'max_acceleration': MAX_ACCEL
    }
    # ego car starts at lane 2, s=0, goal is s=300, lane 0
    road.add_ego(2, 0, ego_config)
    timestep = 0
    # only check if reached GOAL s, if reached check if reached GOAL lane
    # each iteration advance() on sec
    while road.get_ego().s <= GOAL[0]:
        timestep += 1
        if timestep > 150:
            if VISUALIZE:
                print("Taking too long to reach goal. Go faster!")
                break

        road.advance()
        if VISUALIZE:
            print(road)
            time.sleep(float(1.0) / FRAMES_PER_SECOND)
    ego = road.get_ego()
    if VISUALIZE:
        if ego.lane == GOAL[1]:
            print("You got to the goal in {} seconds!".format(timestep))
        else:
            print("You missed the goal. You are in lane {} instead of {}.".format(ego.lane, GOAL[1]))
    return timestep, ego.lane
Exemple #13
0
def readRoads(e, nodes):
    roads = []

    # Desired road types
    driveable = [
        "motorway", "trunk", "primary", "secondary", "tertiary", "residential",
        "service", "living_street", "track", "road", "unclassified"
    ]
    for r in driveable.copy():
        driveable.append(r + "_link")

    # Read all roads/ways into an array
    for road in e.findall('way'):
        r = Road(road.get("id"))

        supported = False

        # Read all information about each road
        for tag in road.findall('tag'):
            setattr(r, tag.get("k").replace(":", "_"), tag.get("v"))

            # Filter out unwanted roads
            if tag.get('k') == "highway":
                if tag.get('v') in driveable:
                    supported = True
        if not supported:
            continue

        # Connect to the nodes
        for nd in road.findall('nd'):
            r.nodes.append(nodes[nd.get("ref")])

        roads.append(r)

    return roads
Exemple #14
0
    def __init__(self):

        self._image_count = 0

        # Camera variables
        self._calibration_images_dir = '../camera_cal/calibration*.jpg'
        self._calibration_images_nx = 9
        self._calibration_images_ny = 6
        self._calibration_matrix = None
        self._initialize_calibration_matrix()

        # Thresholding variables
        self._sx_params = {"Active": True, "Orient": 'x', "Thresh": (20, 190)}
        self._sy_params = {"Active": True, "Orient": 'y', "Thresh": (20, 190)}
        self._sdir_params = {"Active": True, "Thresh": (0.8, 1.5), "Sobel_kernel": 15}
        self._mag_params = {"Active": True, "Thresh": (0, 255), "Sobel_kernel": 3}
        self._s_color_params = {"Active": True, "Thresh": (170, 255)}
        self._thresholder = None
        self._initialize_thresholder()

        # Masking
        self._masker = None
        self._initialize_masker()

        # Perspective transform
        self._perspective_transformer = None
        self._initialize_perspective_transformer()

        # WindowSearch
        self._window_searcher = None
        self._initialize_window_searcher()

        # Road
        self._road = Road()
Exemple #15
0
def main():
    # define display variables
    size = [WIN_SIZE_X, WIN_SIZE_Y]
    screen = pygame.display.set_mode(size)
    done = False
    clock = pygame.time.Clock()

    # define starting variables
    start_pos = np.array([20, size[1] / 2])
    start_dir = 10.0
    god = God(50, start_pos, start_dir)
    road = Road(size, width=50)

    # start a separate "god" evolutionary thread, different than the display update thread
    t = Thread(target=god.run, args=([road]))
    t.start()

    # main loop
    while not done:
        clock.tick(10)

        for event in pygame.event.get():  # User did something
            if event.type == pygame.QUIT:  # If user clicked close
                done = True  # Flag that we are done so we exit this loop

        screen.fill((255, 255, 255))

        road.draw(screen)
        god.draw(screen)

        pygame.display.flip()

    pygame.quit()
def test_add():
    r = Road(1, 2, 3, [Car((0, 1))])
    assert np.all(r.cells == [0, 1, 0])
    r.addCar(Car(), pos=(0, 2))
    assert np.all(r.cells == [0, 1, 1])
    r.addCar(Car())
    assert np.all(r.cells == [1, 1, 1])
Exemple #17
0
def main():
    road = Road(SPEED_LIMIT, TRAFFIC_DENSITY, LANE_SPEEDS)
    road.update_width = AMOUNT_OF_ROAD_VISIBLE
    road.populate_traffic()
    ego_config = config = {
        'speed_limit': SPEED_LIMIT,
        'num_lanes': len(LANE_SPEEDS),
        'goal': GOAL,
        'max_acceleration': MAX_ACCEL
    }
    road.add_ego(2, 0, ego_config)
    timestep = 0
    while road.get_ego().s <= GOAL[0]:
        timestep += 1
        if timestep > 150:
            print "Taking too long to reach goal. Go faster!"
            break
        road.advance()
        print road
        time.sleep(float(1.0) / FRAMES_PER_SECOND)
    ego = road.get_ego()
    if ego.lane == GOAL[1]:
        print "You got to the goal in {} seconds!".format(timestep)
    else:
        print "You missed the goal. You are in lane {} instead of {}.".format(
            ego.lane, GOAL[1])
Exemple #18
0
def build_map(map_arg):
    new_map = [[]]
    map_file = open(map_arg, "r")
    map_file_contents = map_file.read()
    x_index = 0
    y_index = 0
    for c in map_file_contents:
        if c == 'N' or c == 'M' or c == 'B' or c == 'R':
            node = Node(x_index, y_index, c)
            new_map[y_index].append(node)
            x_index += 1
        elif c == '+':
            road = Road(x_index, y_index)
            new_map[y_index].append(road)
            x_index += 1
        elif c == '\n':
            x_index = 0
            y_index += 1
            new_map.append([])
        else:
            new_map[y_index].append(None)
            x_index += 1
    for y, row in enumerate(new_map):
        for x, location in enumerate(row):
            if location:
                if x < len(row) - 1:
                    east_loc = new_map[y][x + 1]
                    if east_loc:
                        location.add_neighbor(Direction.EAST, east_loc)
                if y < len(new_map) - 1 and new_map[y + 1]:
                    south_loc = new_map[y + 1][x]
                    if south_loc:
                        location.add_neighbor(Direction.SOUTH, south_loc)
    return new_map
Exemple #19
0
def peturb_traffic(starting_positions, n_timesteps_before, n_timesteps_slowed,
                   n_timesteps_after, slow_car_num=3):
    '''Allow the simulation to run for a given number of steps before suddenly
    slowing one car and resuming the simulation.

    Args:
        starting_positions: List of starting_position to pass to ``road.add_multiple_cars``
        n_timesteps_before: How many steps to run before the car is slowed
        n_timesteps_slowed: How many steps the car goes at a reduced speed
        n_timesteps_after: How many steps to record after the car has recovered
        slow_car_num: the index of the car to slow, starting at the front of the road

    Returns:
        An array containing the positions of all the cars with time.
    '''
    road = Road()

    # Add the cars and allow them to run for a while
    road.add_multiple_cars(starting_positions, starting_velocity)
    road.run_simulation(n_timesteps_before)

    # Slow a car in the middle of pack
    slowed_car = road.car_list[slow_car_num]
    slowed_car.max_velocity = 20
    slowed_car.velocity = 20

    # Resume the simulation
    road.run_simulation(n_timesteps_slowed)

    # Allow the car to recover
    slowed_car.max_velocity = 60
    road.run_simulation(n_timesteps_after)

    history_position_array = road.get_history_position_array()
    return history_position_array
Exemple #20
0
	def parse(self):
		data = open(u'graph%d' % self.game, u'r').read()
		for line in data.split(u'\n'):
			line = line.strip()
			if not line:
				continue
			line = line.split(u' ')

			self.parsed[int(line[0])][int(line[1])] = True
			self.parsed[int(line[1])][int(line[0])] = True
			try:
				self.connections[int(line[1])][int(line[0])].append(int(line[2]))
				self.connections[int(line[0])][int(line[1])].append(int(line[2]))

			except:
				pass

		data = open(u'roads%d' % self.game, u'r').read()
		for line in data.split(u'\n'):
			line = line.strip()
			if not line:
				continue
			line = line.split(u' ')

			self.roads[int(line[0])] = Road(
				int(line[0]),
				int(line[1]),
				int(line[2]),
				float(line[3]),
				float(line[4]),
				float(line[5]),
			)
def test_init():
    try:
        Road(1, 2, -30, [])
        assert False
    except ValueExpectedException as ex:
        print()
        print(ex.message)
        assert True
Exemple #22
0
    def setup_road(self, start, end, image):
        ''' Sets up a single, 1-D road. '''
        r = Road(start, end, height=self.img_size)

        x_len = int(r.length)  # - self.img_size
        y_len = self.img_size * 2

        s = Sprite(image, (x_len, y_len))

        x = start.x
        y = self.height - start.y

        angle = r.angle

        # force angle between [0, 360)
        while angle < 0:
            angle += 360
        while angle >= 360.0:
            angle -= 360

        # This is the logic for the direction the bmp should face.
        # It's messy because of the way pygame handles PNG's (position is
        #   top left corner of the bmp)
        image_flipped = False
        # DONT ASK
        if 90.0 <= angle < 270.0:
            image_flipped = True
            x = end.x
            y = self.height - end.y

        if angle == 0.0:
            x += self.img_size

        elif angle == 90.0:
            if image_flipped:
                y += self.img_size
            else:
                y -= self.img_size

        elif angle == 180.0:
            if image_flipped:
                x += self.img_size
            else:
                x -= self.img_size

        elif angle == 270.0:
            y += self.img_size

        if angle == 0.0 or angle == 180.0:
            y -= self.img_size / 2
        else:
            x -= self.img_size / 2

        s.move_to(x=x, y=y)
        s.set_angle(angle)

        self.window.add_sprite(s)
        return r
Exemple #23
0
    def parseROAD(self, data):
        data = data.split(u' ')
        id = int(data[0])
        destination = int(data[1])
        speed = float(data[2])
        cost = float(data[3])
        length = float(data[4])

        return Road(id, None, destination, speed, cost, length)
Exemple #24
0
    def __init__(self, *args, **kwargs):
        super(Tester, self).__init__(*args, **kwargs)

        vehicles = []
        vehicles.append({})
        vehicles[0]['id'] = 'truck'
        vehicles[0]['vClass'] = 'truck'
        vehicles[0]['length'] = 15.0
        vehicles[0]['maxSpeed'] = 90.0
        vehicles[0]['accel'] = 1.0
        vehicles[0]['decel'] = 5.0
        vehicles[0]['sigma'] = 0.0
        vehicles.append({})
        vehicles[1]['id'] = 'car'
        vehicles[1]['vClass'] = 'passenger'
        vehicles[1]['length'] = 4.0
        vehicles[1]['maxSpeed'] = 120.0
        vehicles[1]['accel'] = 1.0
        vehicles[1]['decel'] = 5.0
        vehicles[1]['sigma'] = 0.0

        road_params = {}
        road_params['road_type'] = 'intersection'
        road_params['name'] = 'intersection_test'
        road_params['nb_lanes'] = 1
        road_params['nodes'] = np.array([[-200., 0.], [0., 0.], [200., 0.],
                                         [0., -200.], [0., 200.], [-1000, 0],
                                         [1000, 0], [0, -1000], [0, 1000]])
        road_params['priority'] = np.array([[0, 5, 0, 0, 0, 5, 0, 0, 0],
                                            [5, 0, 5, 3, 3, 0, 0, 0, 0],
                                            [0, 5, 0, 0, 0, 0, 5, 0, 0],
                                            [0, 3, 0, 0, 0, 0, 0, 3, 0],
                                            [0, 3, 0, 0, 0, 0, 0, 0, 3],
                                            [5, 0, 0, 0, 0, 0, 0, 0, 0],
                                            [0, 0, 5, 0, 0, 0, 0, 0, 0],
                                            [0, 0, 0, 3, 0, 0, 0, 0, 0],
                                            [0, 0, 0, 0, 3, 0, 0, 0, 0]])
        road_params['edges'] = np.array(road_params['priority'] > 0, dtype=int)
        road_params['routes'] = np.array([[0, 1, 2, 6], [0, 1, 3, 7],
                                          [2, 1, 0, 5], [2, 1, 4, 8],
                                          [3, 1, 4, 8]])
        road_params['vehicles'] = vehicles
        road_params['lane_change_duration'] = 4
        road_params['max_road_speed'] = 35
        road_params['overtake_right'] = True
        road_params['lane_width'] = 3.2
        road_params['emergency_decel_warn_threshold'] = 10

        road_params['collision_action'] = 'warn'
        road_params['no_display_step'] = 'true'

        road_params['view_position'] = np.array([200, 200])
        road_params['view_delay'] = 100
        road_params['zoom'] = 250

        self.road = Road(road_params)
Exemple #25
0
class FuncrashApp(App):
    road = ObjectProperty(Road())

    def build(self):
        self.game = Game(State(self))
        Clock.schedule_interval(self.game.tick, 1.0 / 30.0)
        return self.game

    def on_stop(self):
        self.game.close()
Exemple #26
0
    def read_road_dict(self):
        """
        并初始化最短路径
        :return:
        """
        self.road_dict = dict()
        self.road_id_to_vid_dict = dict()
        self.road_id_set = set()
        road_data = read_items_from_file(ROAD_PATH)
        for road_item in road_data:
            road_item[4] = self.cross_real_id_to_id_dict[road_item[4]]
            road_item[5] = self.cross_real_id_to_id_dict[road_item[5]]
            road = Road(*road_item)

            self.road_dict[road.vid] = road
            self.road_id_to_vid_dict[road_item[0]] = (road_item[4], road_item[5])
            self.road_id_set.add(road_item[0])

            Data.first_dis_arr[road.vid] = road.length / road.speed_limited

            if road.is_duplex:  # 因为会有双向路,而roads_container是按照道路的向量表示的,因此对于双向路要重建一个road类
                road_item[4], road_item[5] = road_item[5], road_item[4]
                road = Road(*road_item)

                self.road_dict[road.vid] = road

                Data.first_dis_arr[road.vid] = road.length / road.speed_limited

        Data.PAYLOAD_OF_MAP = self.PAYLOAD_OF_MAP
        Data.MAX_CARS_ON_MAP = self.MAX_CARS_ON_MAP
        Data.first_dis_arr /= Data.first_dis_arr[np.isfinite(Data.first_dis_arr)].max()
        Data.first_path_arr = get_path_arr(Data.first_dis_arr)  # 需要上一步生成的距离矩阵,并且生成路径矩阵
        Data.path_time_arr = self.get_path_time_arr(Data.first_path_arr)

        self.road_dict = OrderedDict(sorted(self.road_dict.items(), key=lambda x: (x[1].to_cross_id, x[1].id)))
        logging.info({'TotalRoads': self.ROADS_CNT,
                      'ByRoadID': len(road_data),
                      'PayRoadOfMap': self.PAYLOAD_OF_MAP,
                      'MAX_COVERAGE': MAX_COVERAGE,
                      'MAX_CARS_ON_MAP': self.MAX_CARS_ON_MAP
                      })
Exemple #27
0
def map_sprites():

    global decorations
    decorations = pygame.sprite.Group()
    decorations.add(Pond(400, 325))
    decorations.add(Road_2(150, 0))
    decorations.add(Road_2(350, 0))
    decorations.add(Road_2(550, 0))
    decorations.add(Road_2(750, 0))
    decorations.add(Road(0, 75))
    decorations.add(Road(0, 375))
    decorations.add(Road(0, 675))
    decorations.add(Box(5, 5))
    decorations.add(Box(495, 20))
    decorations.add(Box(295, 320))
    decorations.add(Box(95, 130))
    decorations.add(Box(605, 320))
    decorations.add(Box(205, 620))
    decorations.add(Box(695, 430))
    decorations.add(Box(945, 620))
    decorations.add(Box(405, 730))
    decorations.add(Box(805, 745))
    decorations.add(Tower(0, 275))
    decorations.add(Tower(200, 125))
    decorations.add(Tower(950, 275))
    decorations.add(Tower(300, 575))
    decorations.add(Fan(700, 125))
    decorations.add(Fan(950, 125))
    decorations.add(Fan(0, 625))
    decorations.add(Fan(600, 625))
    decorations.add(Fan(300, 0))
    decorations.add(Fan(200, 750))
    decorations.add(Tree(400, 125))
    decorations.add(Tree(500, 625))
    decorations.add(Flower(405, 325))
    decorations.add(Flower(530, 325))
    decorations.add(Flower(465, 300))
    decorations.add(Flower(405, 460))
    decorations.add(Flower(530, 460))
    decorations.add(Flower(465, 480))
    decorations.add(Arrow(875, 25))
Exemple #28
0
def baseRoad(request):
    _ = Road()
    print('\n')
    try:
        lengths = request.param
    except AttributeError:
        lengths = []
    for length in lengths:
        _.addSegment(Segment(length))
        print('adding segment with length {}'.format(length))
    print('road created')
    return _
def test_road_curve():
    test_road = Road(2)
    test_car = Car()
    test_car.speed = 8
    test_car_two = Car(20)
    td = test_road.set_tail_distance(test_car, test_car_two)
    test_car.set_new_speed(test_car_two, td)
    test_car.change_position()
    test_road.check_end_of_lap(test_car)
    test_car.check_position(test_car_two)
    test_road.check_end_of_lap(test_car)
    assert test_car.speed == 10
Exemple #30
0
    def from_config(cls, city_config_path):
        cars_filepath = Path(city_config_path) / cls.CARS_FILE
        with open(cars_filepath, 'r') as f:
            car_records = json.load(f)

        layout_filepath = Path(city_config_path) / cls.LAYOUT_FILE
        with open(layout_filepath, 'r') as f:
            layout = json.load(f)

        schedule_filepath = Path(city_config_path) / cls.SCHEDULE_FILE
        with open(schedule_filepath, 'r') as f:
            schedule = json.load(f)

        lights = {}
        roads = {}
        cars = {}

        for road_record in layout['roads']:
            id = road_record['id']
            length = road_record['length']
            roads[id] = Road(id, length)

        for light_record in layout['lights']:
            id = light_record['id']
            roads_in_ids = light_record['roads_in']
            roads_out_ids = light_record['roads_out']
            for road_in in roads_in_ids:
                roads[road_in].light_out = id
            for road_out in roads_out_ids:
                roads[road_out].light_in = id
            lights[id] = Light(id, roads_in_ids, roads_out_ids)

        for car_record in car_records:
            id = car_record['id']
            road_ids = car_record['roads']

            # TODO: Check that the order of roads is possible

            cars[id] = Car(id, road_ids)

        time_allocated = layout['time_allocated']

        for light_record in schedule:
            light_id = light_record['light']
            signals = []
            for signal_record in light_record['signals']:
                road_id = signal_record['road']
                time = signal_record['time']
                signal = Signal(road_id, time)
                signals.append(signal)
            lights[light_id].signals = signals

        return cls(roads, lights, cars, time_allocated)