Ejemplo n.º 1
0
class NaSchTraffic(Model):
    """
    Model class for the Nagel and Schreckenberg traffic model.
    """
    def __init__(self,
                 height=1,
                 width=60,
                 vehicle_quantity=5,
                 general_max_speed=4,
                 seed=None):
        """"""

        super().__init__(seed=seed)
        self.height = height
        self.width = width
        self.vehicle_quantity = vehicle_quantity
        self.general_max_speed = general_max_speed
        self.schedule = SimultaneousActivation(self)
        self.grid = SingleGrid(width, height, torus=True)

        self.average_speed = 0.0
        self.averages = []
        self.total_speed = 0

        self.datacollector = DataCollector(
            model_reporters={
                "Average_Speed": "average_speed"
            },  # Model-level count of average speed of all agents
            # For testing purposes, agent's individual x position and speed
            agent_reporters={
                "PosX": lambda x: x.pos[0],
                "Speed": lambda x: x.speed,
            },
        )

        # Set up agents
        # We use a grid iterator that returns
        # the coordinates of a cell as well as
        # its contents. (coord_iter)
        cells = list(self.grid.coord_iter())
        self.random.shuffle(cells)
        for vehicle_iter in range(0, self.vehicle_quantity):
            cell = cells[vehicle_iter]
            (content, x, y) = cell
            agent = VehicleAgent((x, y), self, general_max_speed)
            self.grid.position_agent(agent, (x, y))
            self.schedule.add(agent)

        self.running = True
        self.datacollector.collect(self)

    def step(self):
        """
        Run one step of the model. Calculate current average speed of all agents.
        """
        if self.schedule.steps == 100:
            self.running = False
        self.total_speed = 0
        # Step all agents, then advance all agents
        self.schedule.step()
        if self.schedule.get_agent_count() > 0:
            self.average_speed = self.total_speed / self.schedule.get_agent_count(
            )
        else:
            self.average_speed = 0
        self.averages.append(self.average_speed)
        # collect data
        self.datacollector.collect(self)