Home > Back-end >  why first postion in list not changing
why first postion in list not changing

Time:10-13

in this small system of traffic simulation the first position in the list is not changing as you can see:

[.....], (G), [.....]
[.....], (G), [...S.]
[.....], (G), [..SS.]
[.....], (G), [.SSS.]
[...S.], (G), [.SSS.]
[..SS.], (G), [.SSS.]
[.SSS.], (G), [.SSW.]
[.SSS.], (G), [.SWS.]
[.SSS.], (G), [.WSS.]
[.SSW.], (G), [.SSS.]
[.SWS.], (G), [.SSW.]
[.WSS.], (G), [.SWW.]
[.SSS.], (G), [.WWS.]
[.SSW.], (G), [.WSW.]
[.SWW.], (G), [.SWS.]
[.WWS.], (G), [.WSS.]
[.WSW.], (G), [.SSS.]
[.SWS.], (G), [.SSW.]
[.WSS.], (G), [.SWS.]
[.SSS.], (G), [.WSW.]

Final state:
[.SSW.], (G), [.SWW.]

I’m trying to let the cars "which defined by destination S" to show up in the first position as well, something like

[.....] (G) [.....]   []
    [.....] (G) [....S]   []
    [.....] (G) [...SS]   []
    [.....] (G) [..SSS]   []
    [.....] (G) [.SSSS]   []
    [.....] (G) [SSSSS]   []
    [....S] (G) [SSSSW]   []
    [...SS] (G) [SSSWS]   []
    [..SSS] (R) [SSWSS]   []
    [.SSS.] (R) [SSWSS]   ['S']
    [SSS..] (G) [SSWSS]   ['S', 'W']
    [SS..S] (G) [SWSSS]   ['W', 'W']
    [S..SS] (G) [WSSSW]   ['W', 'S']
    [..SSW] (G) [SSSWW]   ['S', 'W']
    [.SSWS] (G) [SSWWS]   ['W', 'S']
    [SSWSS] (G) [SWWSW]   ['S', 'S']
    [SWSSS] (G) [WWSWS]   ['S', 'S']
    [WSSSW] (G) [WSWSS]   ['S', 'W']
    [SSSWW] (R) [SWSSS]   ['W', 'S']
    [SSWW.] (R) [SWSSS]   ['W', 'S', 'W']
    [SWW..] (G) [SWSSS]   ['W', 'S', 'W', 'W']
    [WW..S] (G) [WSSSW]   ['S', 'W', 'W', 'S']
    [W..SW] (G) [SSSWS]   ['W', 'W', 'S', 'W']
    [..SWS] (G) [SSWSW]   ['W', 'S', 'W', 'W']
    [.SWSS] (G) [SWSWW]   ['S', 'W', 'W']
    [SWSSS] (G) [WSWWS]   ['W', 'W', 'S']
    [WSSSW] (G) [SWWSW]   ['W', 'S']
    [SSSWS] (G) [WWSWW]   ['S']
    [SSWSW] (R) [WSWWS]   []
    [SWSW.] (R) [WSWWS]   []
    [WSW..] (G) [WSWWS]   ['W']
    [SW..W] (G) [SWWSW]   ['S']
    [W..WS] (G) [WWSWS]   []
    [..WSW] (G) [WSWS.]   []

Class Destinations is to simulate the arrival of new vehicles to the traffic system. Each call to its step method returns either None, indicating that no vehicle came to this step, or a destination ('W' or 'S'), And this class is handed to me, and I'm not allowed to change it, and I don't understand how it really works if someone can explain it for me please.

Class Light is to represent traffic signals.

Class Lane is a structure that contains a number of vehicles and a number of empty spaces. The vehicles can only enter at the beginning and leave at the end of the lane, i.e. the lane is like a "tube".

Class Vehicle Its task is only to keep track of when the vehicle was created and where it is going.

Class TrafficSystem defines a specific traffic system. It keeps track of which lanes and which signals are included and how the vehicles are to be moved through the system it has:

  1. A constructor which creates the components.

  2. A method step(), which advances all components by one step, moves vehicles in or out of the system, past the lights and between lanes and work like this

    - Remove the first vehicle from the first (left) lane in the figure.
    
    - Step the first lane with its step method.
    
    - If the signal is green, move the first vehicle from the second (right) lane to 
      the first lane.
    
    - Step the traffic signal with its step method.
    
    - Step the second lane.
    
    - Call the step method in the Destinations object - if this returns a destination 
      (i.e. something other than None) then create a vehicle and put it last on the 
      second lane.
    
  3. A method snapshot() that prints a snapshot of the system, and It should be based on t the str() methods from the various components.

4.A method number_in_system() that returns the total number of vehicles currently in the system.

5.A method print_statistics() that prints out some statistics.

The code is:

class Destinations:
    """ Generates a sequence of destinations (None, 'W', 'S') """

    def __init__(self):
        self._arrivals = (  # 0:52, 1:26, 2:22
            2, 2, 2, 2, 2, 1, 2, 2, 2, 1, 1, 2, 1, 2, 2, 2, 1, 2, 1, 1,
            2, 1, 1, 0, 2, 0, 0, 0, 0, 1, 2, 0, 0, 0, 1, 0, 0, 2, 0, 1,
            2, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1,
            0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 2, 0, 0,
            1, 2, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1)

        self._internal_time = 0
        self._total_cycle = len(self._arrivals)

    def step(self):
        ind = self._arrivals[self._internal_time]
        self._internal_time = (self._internal_time   1) % len(self._arrivals)
        return 'W' if ind == 1 else 'S' if ind == 2 else None
# Traffic system components
class Vehicle:
    '''Represents vehicles in traffic simulations
    '''

    def __init__(self, destination, borntime):
        self.destination = destination
        self.borntime = borntime

    def __repr__(self):
        '''A verbose representation
        '''
        return f'Vehicle({self.destination}, {self.borntime})'

    def __str__(self):
        '''A simple representation
        '''
        return self.destination


class Light:
    """Represents a traffic light"""

    def __init__(self, period, green_period):
        self.period = period
        self.green_period = green_period
        self.color = 'G'
        self.time = 0

    def __str__(self):
        return f"({self.color})"

    def step(self):
        self.time  = 1
        if self.time % self.period < self.green_period:
            self.color = 'G'
        else: 
            self.color = 'R'

    def is_green(self):
        if self.color == 'G':
            return True
        elif self.color == 'R':
            return False


class Lane:
    '''Represents a lane with (possible) vehicles
    '''

    def __init__(self, length):
        self.length = length
        self.lane = ['.'] * self.length

    def __str__(self):
        '''Lane representation
        '''
        return '['   ''.join([str(s) for s in self.lane])   ']'

    def enter(self, vehicle):
        self.lane[-1] = vehicle

    def is_last_free(self):
        return self.lane[-1] == '.'

    def step(self):
        '''Implementation of step
        '''
        for i in range(len(self.lane) - 1):
            if self.lane[i] == '.':  # if a spot is empty
                self.lane[i] = self.lane[i   1]  # move next spot forward
                self.lane[i   1] = '.'  # and clear next spot
        self.lane[-1] = '.'  # clear the very last spot

    def get_first(self):
        if self.lane[0] == '.':
            return None
        else:
            return self.lane[0]

    def remove_first(self):
        x = self.lane[0]
        if x == '.':
            return None
        else:
            self.lane[0] = '.'
            return x

    def number_in_lane(self):
        return len(self.lane) - self.lane.count('.')

from statistics import mean, median
from time import sleep
import destinations as ds
import trafficComponents as tc


class TrafficSystem:
    """Defines a traffic system"""

    def __init__(self):
        self.time = 0
        self.destinations = ds.Destinations()
        self.lane_1 = tc.Lane(5)
        self.lane_2 = tc.Lane(5)
        self.light = tc.Light(10, 8)

    def snapshot(self):
        print(
            f"{self.lane_1.__str__()}, {self.light.__str__()}, {self.lane_2.__str__()}")

    def step(self):
        v = tc.Vehicle(str(self.destinations.step()),10)
        self.lane_1.remove_first()
        if self.light.is_green:
            self.lane_2.enter(v)
            self.lane_2.step()
            if self.lane_2.get_first() != None:
                self.lane_1.enter(self.lane_2.remove_first())
                self.lane_1.step()
                self.lane_1.remove_first()
       
        

    def in_system(self):
        pass

    def print_statistics(self):
        pass


def main():
    ts = TrafficSystem()
    for i in range(20):
        ts.snapshot()
        ts.step()
        sleep(0.1)
    print('\nFinal state:')
    ts.snapshot()
    print()
    ts.print_statistics()


if __name__ == '__main__':
    main()

CodePudding user response:

TrafficSystem.step() always removes the first position from lane_1.

    def step(self):
        v = tc.Vehicle(str(self.destinations.step()),10)
        self.lane_1.remove_first()
        if self.light.is_green:
            self.lane_2.enter(v)
            self.lane_2.step()
            if self.lane_2.get_first() != None:
                self.lane_1.enter(self.lane_2.remove_first())
                self.lane_1.step()
                self.lane_1.remove_first()

The first thing it does is self.lane_1.remove_first(), which removes the first element.

Then if the first element of lane_2 is not None, it moves that first element to lane_1, steps lane 1, then removes the first element again.

So whatever the conditions are, the last thing it does to self.lane_1 is remove_first().

I don't understand the simulation so I don't know what you should do to fix it. You need to figure out when you really need to call remove_first().

CodePudding user response:

My mistake was in step() method when ordering the commends.

The code is:

def step(self):
        self.time  = 1
        self.lane_1.remove_first()
        self.lane_1.step()
        if self.light.is_green():
            self.lane_1.enter(self.lane_2.remove_first())
        self.light.step()
        self.lane_2.step()
        self.destinations.step()
        x = self.destinations.step()
        if x != None:
            v = tc.Vehicle(x, self.time)
            self.lane_2.enter(v)

I changed the loop range to 100

the result is:


[.....], (G), [.....]
[.....], (G), [....S]
[.....], (G), [...SS]
[.....], (G), [..SSW]
[.....], (G), [.SSWS]
[.....], (G), [SSWSW]
[....S], (G), [SWSWS]
[...SS], (G), [WSWSS]
[..SSW], (R), [SWSSS]
[.SSW.], (R), [SWSSS]
[SSW..], (G), [SWSSW]
[SW..S], (G), [WSSWW]
[W..SW], (G), [SSWW.]
[..SWS], (G), [SWW..]
[.SWSS], (G), [WW...]
[SWSSW], (G), [W...W]
[WSSWW], (G), [...W.]
[SSWW.], (G), [..W..]
[SWW..], (R), [.W...]
[WW...], (R), [W...S]
[W....], (G), [W..SW]
[....W], (G), [..SW.]
[...W.], (G), [.SW..]
[..W..], (G), [SW...]
[.W..S], (G), [W....]
[W..SW], (G), [....W]
[..SW.], (G), [...W.]
[.SW..], (G), [..W.W]
[SW...], (R), [.W.W.]
[W....], (R), [W.W.W]
[.....], (G), [WW.WW]
[....W], (G), [W.WWW]
[...WW], (G), [.WWW.]
[..WW.], (G), [WWW..]
[.WW.W], (G), [WW..W]
[WW.WW], (G), [W..W.]
[W.WWW], (G), [..W.W]
[.WWW.], (G), [.W.W.]
[WWW..], (R), [W.W.W]
[WW...], (R), [WW.WS]
[W....], (G), [WWWS.]
[....W], (G), [WWS.S]
[...WW], (G), [WS.SW]
[..WWW], (G), [S.SWS]
[.WWWS], (G), [.SWSS]
[WWWS.], (G), [SWSS.]
[WWS.S], (G), [WSS..]
[WS.SW], (G), [SS...]
[S.SWS], (R), [S....]
[.SWS.], (R), [S....]
[SWS..], (G), [S...W]
[WS..S], (G), [...WS]
[S..S.], (G), [..WSS]
[..S..], (G), [.WSSW]
[.S...], (G), [WSSWS]
[S...W], (G), [SSWSW]
[...WS], (G), [SWSWS]
[..WSS], (G), [WSWSS]
[.WSSW], (R), [SWSSS]
[WSSW.], (R), [SWSSS]
[SSW..], (G), [SWSSW]
[SW..S], (G), [WSSWW]
[W..SW], (G), [SSWW.]
[..SWS], (G), [SWW..]
[.SWSS], (G), [WW...]
[SWSSW], (G), [W...W]
[WSSWW], (G), [...W.]
[SSWW.], (G), [..W..]
[SWW..], (R), [.W...]
[WW...], (R), [W...S]
[W....], (G), [W..SW]
[....W], (G), [..SW.]
[...W.], (G), [.SW..]
[..W..], (G), [SW...]
[.W..S], (G), [W....]
[W..SW], (G), [....W]
[..SW.], (G), [...W.]
[.SW..], (G), [..W.W]
[SW...], (R), [.W.W.]
[W....], (R), [W.W.W]
[.....], (G), [WW.WW]
[....W], (G), [W.WWW]
[...WW], (G), [.WWW.]
[..WW.], (G), [WWW..]
[.WW.W], (G), [WW..W]
[WW.WW], (G), [W..W.]
[W.WWW], (G), [..W.W]
[.WWW.], (G), [.W.W.]
[WWW..], (R), [W.W.W]
[WW...], (R), [WW.WS]
[W....], (G), [WWWS.]
[....W], (G), [WWS.S]
[...WW], (G), [WS.SW]
[..WWW], (G), [S.SWS]
[.WWWS], (G), [.SWSS]
[WWWS.], (G), [SWSS.]
[WWS.S], (G), [WSS..]
[WS.SW], (G), [SS...]
[S.SWS], (R), [S....]
[.SWS.], (R), [S....]

Final state:
[SWS..], (G), [S...W]

  • Related