Get startedGet started for free

Modeling a petrol station: Python generators

Consider that a client wants to build a gas station, and you have been asked to create a discrete-event model to help determine the optimal number of gas pumps and the size of the common fuel tank used by the pumps. This model requires simulating the cars arriving at the gas station and the stations' resources: the pumps and the fuel tank. In this exercise, we will focus on the following two steps:

Step 1: Create a generator to simulate the arrival of the cars at the gas station, requesting a pump, and refilling the car tanks.

Step 2: Create a generator to check the level of the tank and request a refill tank when needed. Also, the behavior of the refill tank needs to be modeled.

In the next exercise, you will create the SimPy environment, add processes and resources, and run simulations.

The number of gas pumps are limited and simulated using a SimPy resource stored in the variable gas_station_pumps.

This exercise is part of the course

Discrete Event Simulation in Python

View Course

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

def car(name, env, gas_station_pumps, gas_station_tank):

    fuel_tank_level = random.randint(*FUEL_TANK_LEVEL)
    print(f"{name} arriving at gas station at {env.now}")

    # Request pump
    with gas_station_pumps.____() as req:
        start_time = env.now

        # Yield the pump request
        ____ req

        liters_required = FUEL_TANK_SIZE - fuel_tank_level

        # Remove liters_required from the tank
        yield gas_station_tank.___(liters_required)

        yield env.timeout(liters_required / REFUELING_SPEED)
        print(f"{name} finished refueling in {env.now - start_time} seconds.")
Edit and Run Code