def run():
    if len(sys.argv) < 2:
        print('Please provide the path to the .sumocfg of a SUMO scenario')
        exit()

    print('started')

    ## GUI / CLI
    #     traci.start(["sumo-gui", "-c", sys.argv[1]])
    traci.start(["sumo", "-W", "-c", sys.argv[1]])
    print('traci init')

    step = 0

    startTime = datetime.now()
    print('started at ', startTime.strftime('%Y-%m-%dT%H:%M:%SZ'))
    while traci.simulation.getMinExpectedNumber() > 0:
        traci.simulationStep()
        step += 1

        if (step % 1000 == 0):
            print('\nTime: ',
                  datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ'), '\n')
    traci.close()

    endTime = datetime.now()
    print("Simulation Time:", startTime.strftime('%Y-%m-%dT%H:%M:%SZ'),
          endTime.strftime('%Y-%m-%dT%H:%M:%SZ'), "differnce:",
          (endTime - startTime).strftime('%Y-%m-%dT%H:%M:%SZ'))

    sys.stdout.flush()
Esempio n. 2
0
 def _simulation_start(self):
     self._generate_flow()
     if self.visual == False:
         libsumo.start(self.cmd)
         return
     else:
         traci.start(self.cmd)
         return
Esempio n. 3
0
 def _simulation_start(self):
     if self.visual == False:
         libsumo.start(self.cmd)
         return
     else:
         print('starting ... {}'.format(self.cmd))
         traci.start(self.cmd)
         return
Esempio n. 4
0
    def __init__(self, config):
        """
        Initialize SUMO and sets the beginning of the simulation.

        Param:
            config: Dict. See DEFAULT_CONFIG.
        """
        self._config = config

        # logging
        level = logging.getLevelName(config["log_level"])
        logger.setLevel(level)

        # libsumo vs TraCI selection
        if config["sumo_connector"] == "libsumo":
            import libsumo as traci
        elif config["sumo_connector"] == "traci":
            import traci
        else:
            raise Exception(
                "ERROR: '{}' is not a valid option for 'sumo_connector'. "
                "The possible connectors are 'traci' or 'libsumo'.".format(
                    config["sumo_connector"]))

        # TraCI Handler and SUMO simulation
        logger.debug("Starting SUMOConnector in process %d.", os.getpid())
        self._sumo_label = "{}".format(os.getpid())
        self._sumo_output_prefix = "{}{}".format(config["sumo_output"],
                                                 self._sumo_label)
        self._sumo_parameters = ["sumo", "-c", config["sumo_cfg"]]
        if config["sumo_gui"] and config["sumo_connector"] == "traci":
            self._sumo_parameters[0] = "sumo-gui"
            self._sumo_parameters.extend(["--start", "--quit-on-end"])
        if config["sumo_params"] is not None:
            self._sumo_parameters.extend(config["sumo_params"])
        self._sumo_parameters.extend(
            ["--output-prefix", self._sumo_output_prefix])
        logger.debug("SUMO command line: %s", str(self._sumo_parameters))
        if config["trace_file"]:
            traci.start(
                self._sumo_parameters,
                traceFile="{}.tracefile.log".format(self._sumo_output_prefix),
            )
        else:
            traci.start(self._sumo_parameters)
        self.traci_handler = traci
        # From now on, the call must always be to self.traci_handler

        self._is_ongoing = True
        self._start_time = self.traci_handler.simulation.getTime()
        self._sumo_steps = 0
        self._manually_stopped = False

        # Initialize simulation
        self._initialize_simulation()

        # Initialize metrics
        self._initialize_metrics()
Esempio n. 5
0
def run():
    if len(sys.argv) < 2:
        print('Please provide the path to the .sumocfg of a SUMO scenario')
        exit()

    influx_host = INFLUX_HOST
    influx_port = INFLUX_PORT

    if len(sys.argv) == 4:
        influx_host = sys.argv[2]
        influx_port = int(sys.argv[3])

    print('started')
    client = InfluxDBClient(influx_host, influx_port, 'admin', 'admin')
    client.drop_database(SUMO_DB)
    client.create_database(SUMO_DB)
    client.switch_database(SUMO_DB)
    print('client available')

    ## GUI / CLI
#     traci.start(["sumo-gui", "-c", sys.argv[1]])
    traci.start(["sumo", "-c", sys.argv[1]])
    print('traci init')

    step = 0

    startTime = datetime.now()
    print('started at ', startTime.strftime('%Y-%m-%dT%H:%M:%SZ'))
    while traci.simulation.getMinExpectedNumber() > 0:
        traci.simulationStep()
        departed_ids = traci.simulation.getDepartedIDList()

        # ALL VEHICLES
        [subscribe(x) for x in departed_ids]

        # ONLY BUS
        # [subscribe(x) for x in departed_ids if traci.vehicle.getTypeID(x) == 'bus']

        subscription_results = traci.vehicle.getAllSubscriptionResults()
        vehicles = [subscriberToInfluxJson(
            id, subscription_results[id]) for id in subscription_results]
        client.write_points(vehicles)
        step += 1

        if(step % 1000 == 0):
            print('\n', 'Subscriptions: ', len(subscription_results))
            print('Time: ', datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ'))
    traci.close()

    endTime = datetime.now()
    print("Simulation Time:",
          startTime.strftime('%Y-%m-%dT%H:%M:%SZ'),
          endTime.strftime('%Y-%m-%dT%H:%M:%SZ'),
          "differnce:",
          (endTime - startTime).strftime('%Y-%m-%dT%H:%M:%SZ'))

    sys.stdout.flush()
Esempio n. 6
0
    def __init__(self, config):
        """
        Initialize SUMO and sets the beginning of the simulation.

        Param:
            config: Dict. See DEFAULT_CONFIG.
        """
        self._config = config

        # logging
        level = logging.getLevelName(config['log_level'])
        logger.setLevel(level)

        # libsumo vs TraCI selection
        if config['sumo_connector'] == 'libsumo':
            import libsumo as traci
        elif config['sumo_connector'] == 'traci':
            import traci
        else:
            error = 'ERROR: "{}" is not a valid option for "sumo_connector".'.format(
                config['sumo_connector'])
            error += ' The possible connectors are "traci" or "libsumo".'
            raise Exception(error)

        # TraCI Handler and SUMO simulation
        logger.debug('Starting SUMOConnector in process %d.', os.getpid())
        self._sumo_label = '{}'.format(os.getpid())
        self._sumo_output_prefix = '{}{}'.format(config['sumo_output'], self._sumo_label)
        self._sumo_parameters = ['sumo', '-c', config['sumo_cfg']]
        if config['sumo_gui'] and config['sumo_connector'] == 'traci':
            self._sumo_parameters[0] = 'sumo-gui'
            self._sumo_parameters.extend(['--start', '--quit-on-end'])
        if config['sumo_params'] is not None:
            self._sumo_parameters.extend(config['sumo_params'])
        self._sumo_parameters.extend(['--output-prefix', self._sumo_output_prefix])
        logger.debug('SUMO command line: %s', str(self._sumo_parameters))
        if config['trace_file']:
            traci.start(self._sumo_parameters,
                        traceFile='{}.tracefile.log'.format(self._sumo_output_prefix))
        else:
            traci.start(self._sumo_parameters)
        self.traci_handler = traci
        ## From now on, the call must always be to self.traci_handler

        self._is_ongoing = True
        self._start_time = self.traci_handler.simulation.getTime()
        self._sumo_steps = 0
        self._manually_stopped = False

        # Initialize simulation
        self._initialize_simulation()

        # Initialize metrics
        self._initialize_metrics()
Esempio n. 7
0
    def reset(self):
        libsumo.close()
        libsumo.start(['-c', self.sumocfg])
        self.cars = {}
        self.state = []
        self.action = 0
        self.e_step = 0
        self.changing = 0
        self.light = libsumo.trafficlight.getIDList()[0]
        libsumo.trafficlight.setRedYellowGreenState(
            self.light, self.red_yellow_green[self.action])

        state = self.state_to_grid(self.state, self.action, self.changing)
        norm_timestep = self.e_step / (self.episode_length / 2) - 1
        return (state, norm_timestep), self.state
Esempio n. 8
0
def simOne(simTimes, TM):
    print(str(simTimes) + "\n")
    lateralResolution = 0.01

    path = os.getcwd()
    path2 = path + "\sumoCfg\my1LaneMap1NoVeh-server.sumocfg"
    sumoBinary = "sumo-gui.exe"
    sumoBinary = "sumo.exe"

    libsumo.start([sumoBinary, "-c", path2])

    TM.scenarioLoaded()

    # traci.vehicle.add(str,'r1',-3,0,3,0,'EBus');
    # %'routeID','depart','pos','speed','lane','typeID''for

    #for i in range(len(TM.vehQue)):
    #    veh = TM.vehQue[i]
    #    veh.speed = 0
    #    traci.vehicle.addLegacy(str(veh.id),"r1",-3,veh.position,veh.speed,veh.lane,"EBUS")

    stepNum = 0
    requireStop = 0
    while requireStop == 0:
        stepNum += 1
        [TM, stepNum, requireStop] = runOneStepSUMOSim(TM, stepNum)

    libsumo.close()

    srcFile = path + "\sumoCfg" + "\edge_N1.xml"
    destFile = path + "\sumoCfg" + "\edge_N1_" + str(simTimes) + "_" + str(
        TM.isSplit) + "_" + str(TM.isSC) + ".xml"
    os.rename(srcFile, destFile)

    srcFile = path + "\sumoCfg" + "\edge_N1_FuelEmiss.xml"
    destFile = path + "\sumoCfg" + "\edge_N1_FuelEmiss_" + str(
        simTimes) + "_" + str(TM.isSplit) + "_" + str(TM.isSC) + ".xml"
    os.rename(srcFile, destFile)

    srcFile = path + "\sumoCfg" + "\summary.xml"
    destFile = path + "\sumoCfg" + "\summary_" + str(simTimes) + "_" + str(
        TM.isSplit) + "_" + str(TM.isSC) + ".xml"
    os.rename(srcFile, destFile)

    return
Esempio n. 9
0
    def reset(self):
        """Resets the state of the environment and returns an initial observation.

        Returns: observation (object): the initial observation of the
            space.
        """
        traci.close()

        traci.start(self.cmd)
        self._step = self.begin_time
        # Begin with action id of 1 
        if not self.idle:
            self._action = 1
            self._setTrafficLights(self._action)
        else:
            self._action = self._getTrafficLights()
        
        return (np.zeros(shape=(21,)), 1)
Esempio n. 10
0
    def __init__(self, config_path, episode_length=200, scale=2):
        self.sumocfg = config_path

        self.scale = scale
        self.nA = 2
        background, shift = get_background('simpĺe.net.xml', scale=self.scale)
        self.background = background
        self.shift = shift

        net = sumolib.net.readNet('simpĺe.net.xml')
        self._bounding_box = np.array(net.getBBoxXY())

        self.cars = {}
        self.state = None
        self.action = None
        self.red_yellow_green = ['rrrGGGgrrrGGGg', 'GGgrrrrGGgrrrr']
        self.episode_length = episode_length
        self.yellow_length = 3

        libsumo.start(['-c', self.sumocfg])
        self.edges = libsumo.edge.getIDList()
        libsumo.close()
Esempio n. 11
0
    print("#stopend", traci.simulation.getStopEndingVehiclesNumber())
    print("stopend", traci.simulation.getStopEndingVehiclesIDList())
    print("#colliding", traci.simulation.getCollidingVehiclesNumber())
    print("colliding", traci.simulation.getCollidingVehiclesIDList())
    print("min#expected", traci.simulation.getMinExpectedNumber())
    print("#teleportStart", traci.simulation.getStartingTeleportNumber())
    print("teleportStart", traci.simulation.getStartingTeleportIDList())
    print("#teleportEnd", traci.simulation.getEndingTeleportNumber())
    print("teleportEnd", traci.simulation.getEndingTeleportIDList())


def ppStages(comment, stages):
    print("%s\n  %s\n" % (comment, "\n  ".join(map(str, stages))))


traci.start([sumolib.checkBinary('sumo'), "-c", "sumo.sumocfg"])
traci.simulation.subscribe((traci.constants.VAR_LOADED_VEHICLES_IDS,
                            traci.constants.VAR_DEPARTED_VEHICLES_IDS))
print(traci.simulation.getSubscriptionResults())
for step in range(6):
    print("step", step)
    traci.simulationStep()
    print(traci.simulation.getSubscriptionResults())
checkVehicleStates()
print("deltaT", traci.simulation.getDeltaT())
print("boundary", traci.simulation.getNetBoundary())
print("convertRoad2D", traci.simulation.convert2D("o", 0.))
print("convertRoad3D", traci.simulation.convert3D("o", 0.))
print("convertRoadGeo", traci.simulation.convert2D("o", 0., toGeo=True))
print("convertRoadGeoAlt", traci.simulation.convert3D("o", 0., toGeo=True))
print("convert2DGeo", traci.simulation.convertGeo(488.65, 501.65))
Esempio n. 12
0
from __future__ import print_function
from __future__ import absolute_import
import os
import sys

SUMO_HOME = os.path.join(os.path.dirname(__file__), "..", "..", "..", "..",
                         "..")
sys.path += [os.path.join(SUMO_HOME, "tools"), os.path.join(SUMO_HOME, "bin")]
if len(sys.argv) > 1:
    import libsumo as traci  # noqa
else:
    import traci  # noqa
import sumolib  # noqa

traci.start([
    sumolib.checkBinary('sumo'), "-c", "sumo.sumocfg", '--pedestrian.model',
    'nonInteracting'
])
for step in range(3):
    print("step", step)
    traci.simulationStep()
print("edges", traci.edge.getIDList())
print("edge count", traci.edge.getIDCount())
edgeID = "2fi"
print("examining", edgeID)
print("laneNumber", traci.edge.getLaneNumber(edgeID))
print("adaptedTraveltime", traci.edge.getAdaptedTraveltime(edgeID, 0))
print("effort", traci.edge.getEffort(edgeID, 0))
print("CO2", traci.edge.getCO2Emission(edgeID))
print("CO", traci.edge.getCOEmission(edgeID))
print("HC", traci.edge.getHCEmission(edgeID))
print("PMx", traci.edge.getPMxEmission(edgeID))
Esempio n. 13
0
    def start_simulation(self, scenario, sim_params):
        """Start a sumo simulation instance.

        This method uses the configuration files created by the scenario class
        to initialize a sumo instance. Also initializes a traci connection to
        interface with sumo from Python.
        """
        error = None
        for _ in range(RETRIES_ON_ERROR):
            try:
                # port number the sumo instance will be run on
                port = sim_params.port

                sumo_binary = "sumo-gui" if sim_params.render is True \
                    else "sumo"

                # command used to start sumo
                sumo_call = [
                    sumo_binary,
                    "-c",
                    scenario.cfg,
                    "--remote-port",
                    str(sim_params.port),
                    "--num-clients",
                    str(sim_params.num_clients),
                ]

                logging.info(" Starting SUMO on port " + str(port))
                logging.debug(" Cfg file: " + str(scenario.cfg))
                if sim_params.num_clients > 1:
                    logging.info(" Num clients are" +
                                 str(sim_params.num_clients))
                logging.debug(" Step length: " + str(sim_params.sim_step))

                if sim_params.render:
                    # Opening the I/O thread to SUMO
                    self.sumo_proc = subprocess.Popen(sumo_call,
                                                      preexec_fn=os.setsid)

                    # wait a small period of time for the subprocess to
                    # activate before trying to connect with traci
                    if os.environ.get("TEST_FLAG", 0):
                        time.sleep(0.1)
                    else:
                        time.sleep(config.SUMO_SLEEP)

                    traci_connection = traci.connect(port, numRetries=100)
                    traci_connection.setOrder(0)
                    traci_connection.simulationStep()
                else:
                    # Use libsumo to create a simulation instance.
                    libsumo.start(sumo_call[1:3])
                    libsumo.simulationStep()

                    # libsumo will act as the kernel API
                    traci_connection = libsumo

                return traci_connection
            except Exception as e:
                print("Error during start: {}".format(traceback.format_exc()))
                error = e
                self.teardown_sumo()
        raise error
Esempio n. 14
0
import libsumo
from dummy_agent import DummyAgent
from simulation_runner import SimulationRunner
from reward_extractor import RewardExtractor
from state_representation import StateExtractor

SUMO_CMD = ["-C", "/AI_project/nets/complex_net/config.sumocfg"]

# docker command example:
#       docker run --name <container_name> --rm -it -v <LOCAL_PATH_TO_PROJECT>/AI_project:/AI_project
# <sumo_image>:<tag> bash
#

if __name__ == '__main__':
    libsumo.start(SUMO_CMD)
    agents = [DummyAgent("0"), DummyAgent("1")]
    sr = SimulationRunner(agents, SUMO_CMD, StateExtractor, RewardExtractor)
    sr.initialize_simulation()
    for i in range(1000):
        observations = sr.run_step([agent.get_action() for agent in agents])
        print(observations)
Esempio n. 15
0
 traci.start([
     sumoBinary,
     '-c',
     CONFIG_FILE,
     '-a',
     '{},{}'.format(EDITED_FILE, DETECTOR_FILE),
     '--time-to-teleport',
     '-1',
     #'--no-internal-links', 'true',  #invisible cars
     '--ignore-junction-blocker',
     '-1',  #doesn't really matter
     #'--collision.action', 'none',
     #'--collision.check-junctions', 'true',
     #'--collision.stoptime', '15',
     #'--collision.mingap-factor', '0.2',
     '--random',
     'false',
     '--seed',
     SEED,
     '--start',
     'true',
     '--quit-on-end',
     'true',
     '--no-warnings',
     'true',
     '--eager-insert',
     'true',
     '--step-length',
     STEP_LENGTH,
     '--gui-settings-file',
     VIEW_FILE,
     '--time-to-impatience',
     IMPATIENCE_TIME,
 ])
Esempio n. 16
0
##                   '--random', 'false',
##                   '--seed', SEED,
##                   '--start','true',
##                   '--quit-on-end','true',
##                   '--no-warnings', 'true',
##                   '--eager-insert', 'true',
##                   '--step-length', STEP_LENGTH,
##                   '--gui-settings-file', VIEW_FILE,
##                   '--time-to-impatience', IMPATIENCE_TIME,
##                   ])

    #for SUMO 0.30.0
    traci.start([sumoBinary, '-c', CONFIG_FILE,
                  # '-a', '{},{}'.format(EDITED_FILE, DETECTOR_FILE),
                 '-a', '{}'.format(EDITED_FILE),
                 '--no-internal-links', 'true', 
                   '--time-to-teleport', '-1',
                   '--ignore-junction-blocker', '-1',
                   '--random', 'false',
                   '--seed', SEED,
                   '--start','true',
                   #'--quit-on-end','true',
                   '--no-warnings', 'true',
                   '--step-length', STEP_LENGTH,
                   '--gui-settings-file', VIEW_FILE,
                   '--time-to-impatience', IMPATIENCE_TIME,
                   ])
    main()
    
    
Esempio n. 17
0
# -*- coding: utf-8 -*-
import libsumo

map_file = 'map/1-intersection/traffic.net.xml'
route_file = 'map/1-intersection/traffic.rou.xml'
cmd = ['sumo', '--net-file', map_file, '--route-files', route_file]

libsumo.start(cmd)
print vars(libsumo.simulation)
libsumo.close()

libsumo.start(cmd)
 
Esempio n. 18
0
    parser.add_argument('--b', default=1., type=float)
    parser.add_argument('--c', default=1, type=float)
    parser.add_argument('--delta', default=.99, type=float)
    parser.add_argument('--episodes', default=1500000, type=int)

    args = parser.parse_args()
    print(args)

    background, shift = get_background(
        'simulation_files/networks/simple.net.xml')

    net = sumolib.net.readNet('simulation_files/networks/simple.net.xml')
    bounding_box = net.getBBoxXY()

    sumocfg = "simulation_files/networks/simple.net.xml"
    libsumo.start(['-c', sumocfg])
    edges = libsumo.edge.getIDList()
    print(edges)
    libsumo.close()
    '''

    all_episodes = []
    for step_range in range(1, 150, 3):
        total_reward = step = action = 0
        action = 1
        s = env.reset()
        terminal = False
        mistakes = 0; total_est = 0
        while not terminal:
            if step % step_range == 0:
                action = not action
Esempio n. 19
0
    def __init__(self, env_config):
        print("i have env_config " , env_config)
        self.alpha = env_config['alpha']
        self.beta = env_config['beta']
        self.name = env_config['name'] # for pickle
        self.load = float(env_config['load'])
        self.idle = env_config.get('idle', False)         # this is for baseline (no action)
        self.reward_weight = env_config.get('reward_weight', 'total-cellCap')
        
        print("i am defining action space")
        # Define action space and observation space
        self.action_space = spaces.Discrete(9)

        # Map between action id and RedYellowGreen state
        #     First four 'G's are for cones
        self.action_map = {
            1: "GGGGrrrrgGGGGGGGGGGGGGGGGgggrrrrrrrrrrrrrGGGGGGGGGGGGGGGG",
            2: "GGGGrrrrgrrrrrrrrrrrrrrrrgggGGGGGGGGGGGGGrrrrrrrrrrrrrrrr",
            3: "GGGGGGGGgrrrrrrrrrrrrrrrrgggrrrrrrrGGGGGGrrrrrrrrrrrrrrrr",
            4: "GGGGrrrrgrrrrrrrrrrrrrrrrgggrrrrrrrrrrrrrGGGGGGGGGGGGGGGG",
            5: "GGGGrrrrgGGGGGGGGGGGGGGGGgggrrrrrrrrrrrrrrrrrrrrrrrrrrrrr",
            6: "GGGGrrrrgrrrrrrrrrrrrrrrrgggGGGGGGGrrrrrrrrrrrrrrrrrrrrrr",
            7: "GGGGrrrrgrrrrrrrrrrrrrrrrgggrrrrrrrGGGGGGrrrrrrrrrrrrrrrr",
            8: "GGGGGGGGgrrrrrrrrrrrrrrrrgggrrrrrrrrrrrrrrrrrrrrrrrrrrrrr",
            0: "GGGGrrrrgrrrrrrrrrrrrrrrrgggrrrrrrrrrrrrrrrrrrrrrrrrrrrrr",
            }
        #Map between RedYellowGreenState to actionid
        self.map_action = {v:i for i,v in self.action_map.items()}

        # Map between action id and chosen observation space (for red light delay)
        self.action_obs_map = {
            # choose all
            -1 : [0,1,2,5,6,7,9,10,11,13,14,15],
            0 : [0,1,2,5,6,7,9,10,11,13,14,15],
            1 : [0,1,2,5,6,7] ,             # surasak and charoenRat
            2 : [5,6,7,9,10,11,13,14,15],   # charoenRat, sathornS, sathornN
            3 : [9,10,11,13,14,15],         # sathornS, sathornN
            4 : [0,1,2,5,6,7,9,10,11],      # surasak, charoenRat, sathornS
            5 : [0,1,2,5,6,7,13,14,15],     # surasak, charoenRat, sathornN
            6 : [5,6,7,9,10,11,13,14,15],   # charoenRat, sathornS, sathornN
            7 : [5,6,7,9,10,11,13,14,15],   # charoenRat, sathornS, sathornN
            8 : [0,1,2,9,10,11,13,14,15],   # surasak, sathornS, sathornN
        }
        self._INDEX = np.array([1,2,3]*4)
        
        # Map between action id and downstream edge (for use in throughput)
##        DISCARDED since what about always green?
##        self.action_downstream_edge_map = {
##            1: (edge_sathornN_down[0], edge_sathornS_down[0]),
##            2: (edge_sathornS_down[0], edge_surasak_down[0]),
##            3: (),
##            4: ,
##            5: ,
##            6: ,
##            7: ,
##            8: ,
##            0: (),
##            }

        print("i am defining observation space")
        if env_config['observation_space'] == "no_downstream":
            self.observation_space = spaces.Tuple((spaces.Box(low=0, high=100, shape=(18,), dtype=np.float16),
                                                  self.action_space ))
        elif env_config['observation_space'] == "all3_no_downstream":
            self.observation_space = spaces.Tuple((spaces.Box(low=0, high=100, shape=(12,), dtype=np.float16),
                                                  self.action_space ))
        elif env_config['observation_space'] == "all3":
            self.observation_space = spaces.Tuple((spaces.Box(low=0, high=100, shape=(15,), dtype=np.float16),
                                                  self.action_space ))
        elif env_config['observation_space'] == "default":
            self.observation_space = spaces.Tuple((spaces.Box(low=0, high=100, shape=(21,), dtype=np.float16),
                                                  self.action_space ))

        else:
            error.Error("Define Observation Space in env_config")

        print("i am setting configurations")
        # Set up all Configurations
        self.root_dir = os.path.dirname(os.path.realpath(__file__))
        self.config_file = '{}/models/sathorn-{}/sathorn_w_great_load{}.sumo.cfg'.format(self.root_dir,env_config['time_select'],self.load) \
                           if (env_config['time_select'] == "morning" and env_config['great_edition']) \
                           else '{}/models/sathorn-{}/sathorn_w.sumo.cfg'.format(self.root_dir, env_config['time_select'])
        self.net_file = '{}/models/sathorn-{}/sathorn_w_fixed_20160404.net.xml'.format(self.root_dir, env_config['time_select'])
        self.edited_file = '{}/models/sathorn-{}/sathon_wide_tls_20160418_edited.add.xml'.format(self.root_dir, env_config['time_select'])
        self.view_file = '{}/gui-settings/gui-settings-file-loop.xml'.format(self.root_dir) if (env_config['viewport'] == "whole_loop") \
                         else '{}/gui-settings/gui-settings-file-surasak.xml'.format(self.root_dir)
        self.detector_file = '{}/detectors/sathorn_w_detectors.add.xml'.format(self.root_dir)
        print("I am checking if there is path {}".format(os.path.join(os.path.split(self.detector_file)[0], 'output')))
        if not os.path.exists(os.path.join(os.path.split(self.detector_file)[0], 'output')):
            print("There is no path {}, Building ...".format(os.path.join(os.path.split(self.detector_file)[0], 'output')))
            os.makedirs(os.path.join(os.path.split(self.detector_file)[0], 'output'))
        self.begin_time = 21600 if (env_config['time_select'] == "morning") else 53100
        self.end_time   = 32400 if (env_config['time_select'] == "morning") else 69300
        self.seed = str(env_config['seed'])
        self.step_length = str(env_config['step_length'])
        self.impatience_time = str(env_config['impatience_time'])
        self.time_to_teleport = str(env_config['time_to_teleport'])
        self.no_internal_links = "true" if env_config['no_internal_links'] else "false"
        self.step_size = env_config['step_size']

        self.cell_capacities = np.array(cell_capacities_surasak + cell_capacities_charoenRat + cell_capacities_sathornS + cell_capacities_sathornN)
        
        # Libsumo doesn't have class 'trafficlights' but name class 'trafficlight' instead
        self._trafficlights = traci.trafficlight if WITH_LIBSUMO and not WITH_GUI else traci.trafficlights
        
        # Begin SUMO
        sumoBinary = sumolib.checkBinary('sumo-gui') if env_config['with_gui'] else sumolib.checkBinary('sumo')
        print("Loading Config File {}".format(self.config_file))
        print("Loading Edited File {}".format(self.edited_file))

        self.cmd = [sumoBinary, '-c', self.config_file,
                  '-a', '{},{}'.format(self.edited_file, self.detector_file),
##                 '-a', '{}'.format(self.edited_file),
                   '--no-internal-links', self.no_internal_links, 
                   '--time-to-teleport', self.time_to_teleport,
                   '--ignore-junction-blocker', '-1',
                   '--random', 'false',
                   '--seed', self.seed,
                   '--start','true',
                   '--eager-insert', 'true',
                   '--quit-on-end','true',
                   '--no-warnings', 'true',
                   '--step-length', self.step_length ,
                   '--gui-settings-file', self.view_file,
                   '--time-to-impatience', self.impatience_time ,
                   ]
        
        print("starting traci with command" , " ".join(self.cmd))
        traci.start(self.cmd)
        self._step = self.begin_time
        # Begin with action id of 1 if not idle
        if not self.idle:
            self._action = 1
            self._setTrafficLights(self._action)
        else:
            self._action = self._getTrafficLights()