Esempio n. 1
0
def main():
    args = parse_args()
    confPath = os.path.join(cwd_path, args.conf)
    scenarioPath = os.path.join(cwd_path, args.scenario)
    print('args', args)
    print('conf path', confPath)
    print('scenario path', scenarioPath)

    #confJson = getJsonObj(confPath)
    #print('conf json', confJson)
    #scenarioJson = getJsonObj(scenarioPath)
    #print('scenario json', scenarioJson)

    # ======================================

    libsalt.start(scenarioPath)
    #libsalt.setCurrentStep(25200)
    step = libsalt.getCurrentStep()
    while step <= 87000:
        libsalt.simulationStep()
        step = libsalt.getCurrentStep()

    libsalt.close()
    print("Python: Simulation End!!!")

    # ======================================

    exit(0)
Esempio n. 2
0
def test(salt_scenario):
    libsalt.start(salt_scenario)

    step = libsalt.getCurrentStep()
    while step <= 5000:
        if (step % 1000 == 0):
            print("Simulation Step: {}".format(step))
        libsalt.simulationStep()
        step = libsalt.getCurrentStep()

    libsalt.close()
    print("Python: Simulation End!!!")
Esempio n. 3
0
def test(salt_scenario):
    libsalt.start(salt_scenario)
    libsalt.setCurrentStep(25200)
    step = libsalt.getCurrentStep()
    while step <= 36000:
        if (step % 100 == 0):
            print("Simulation Step: ", step)
            test_funcs()
        libsalt.simulationStep()
        step = libsalt.getCurrentStep()

    libsalt.close()
    print("Python: Simulation End!!!")
def test_changeTLPhaseVector(salt_cfg):
    logger = __get_logger()

    logger.debug('[TEST-LIBSALT] DEBUG LOGs >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
    logger.debug("The SALT Scenario File: {}".format(salt_cfg))

    # 1. Start the SALT
    libsalt.start(salt_cfg)

    # TODO: 2. Check the Begin & End of the simulation
    step = 0

    # 3. Define the target Traffic Signal
    # targetTLNode = "cluster_572701114_572701116_572701117_572712746_572712755"   # For Gandong-gu, Seoul
    targetTLNode = "cluster_563103641_563103889_563103894_563103895"  # For Doan, Daejeon

    # 4. Get the Traffic Signal Information (e.g. schdules)  using get function
    tl = libsalt.trafficsignal.getTLSByNodeID(targetTLNode)

    logger.debug("[Connected Link IDs] {} ".format(
        libsalt.trafficsignal.getTLSConnectedLinkID(targetTLNode)))

    logger.debug("[Target Traffic Signal ID] {}".format(tl.myTLSID))
    logger.debug(
        "The Number of schedules in the target traffic signal: {}".format(
            tl.getScheduleMap().size()))
    tsm = tl.getScheduleMap()
    currentts = libsalt.trafficsignal.getCurrentTLSScheduleByNodeID(
        targetTLNode)
    currenttsid = libsalt.trafficsignal.getCurrentTLSScheduleIDByNodeID(
        targetTLNode)

    if logger.isEnabledFor(logging.DEBUG):
        logger.debug(
            "The Schedule IDs in the target traffic signal: {}".format(
                tsm.keys()))
        logger.debug("The Schedule Detailed >>>>>> ")
        for k in tsm.keys():
            logger.debug("[schedule id: {}]".format(k))
            for p in tsm[k].getPhaseVector():
                logger.debug("phase = ({}), duration = {}".format(p[0], p[1]))
        logger.debug("The Phase Vector in Schedule {}  >>>>>>>>>>>>>>".format(
            tsm.keys()[0]))
        tsps = libsalt.trafficsignal.getTLSPhasesByNodeID(
            targetTLNode,
            tsm.keys()[0])
        for pp in tsps:
            logger.debug("({}, {})".format(pp[0], pp[1]))

        # logger.debug("The Phase Index {}".format(3))
        # tp = libsalt.trafficsignal.getTLSPhaseByNodeID(targetTLNode,tsm.keys()[0],3)
        # logger.debug("({}, {})".format(tp[0], tp[1]))

    # 5. Test Scenario
    # >>> 1) define changing rule (e.g. changing order, testing scenarios)
    # >>> 2) test the changeTLPhase function & show results
    # >>> [test example] every 30 step, changing the phase vector to new one
    triggerduration = 1000
    orderdic = {}
    turn = 0
    # for k in tsm.keys():
    #     for p in enumerate(tsm[k].getPhaseVector()):
    #         if p[1][0] > 5:
    #             pair = []
    #             pair.append(k)
    #             pair.append(p[0])
    #             orderdic[turn] = pair
    #             turn+=1
    # logger.debug("The order of phases: {}".format(orderdic))

    # print(currentts.getPhaseVector())

    for iter in range(5):
        newpv = libsalt.TLSPhaseVector()
        for p in currentts.getPhaseVector():
            # print(p)
            if p[0] > 5:
                newp = libsalt.TLSPhasePair((p[0] + iter + 1, p[1]))
                newpv.append(newp)
            else:
                orip = libsalt.TLSPhasePair(p)
                newpv.append(orip)
        orderdic[iter] = newpv

    logger.debug('[Candidate PhaseVector]: \n')
    for ti in orderdic.keys():
        logger.debug("[oderdic key: {}]".format(ti))
        for tp in orderdic[ti]:
            logger.debug("phase = ({}), duration = {}".format(tp[0], tp[1]))

    while step <= 7200:
        curstep = libsalt.getCurrentStep()

        if (curstep % triggerduration) == 0:
            ordering = (curstep / triggerduration) % len(orderdic)
            # curscheduleid = orderdic[ordering][0]
            # curphaseindex = orderdic[ordering][1]
            curscheduleid = libsalt.trafficsignal.getCurrentTLSScheduleIDByNodeID(
                targetTLNode)
            curphaseindex = libsalt.trafficsignal.getCurrentTLSPhaseStateByNodeID(
                targetTLNode)
            if logger.isEnabledFor(logging.DEBUG):
                logger.debug(
                    "[Trigger Point] time: {}, schdule id: {}  ({})".format(
                        curstep, curscheduleid, curphaseindex))
            libsalt.trafficsignal.setTLSPhaseVector(curstep, targetTLNode,
                                                    curscheduleid,
                                                    orderdic[ordering])
            # libsalt.trafficsignal.setTLSPhaseVector(curstep, targetTLNode, curscheduleid, curphaseindex, orderdic[ordering])
            if logger.isEnabledFor(logging.DEBUG):
                logger.debug("[After Changing] schedule id : {} ({})".format(
                    libsalt.trafficsignal.getCurrentTLSScheduleIDByNodeID(
                        targetTLNode),
                    libsalt.trafficsignal.getCurrentTLSPhaseStateByNodeID(
                        targetTLNode)))

        libsalt.simulationStep()
        step += 1

    libsalt.close()
    logger.debug("simulation end!!!")
def test_setTLS(salt_cfg):
    logger = __get_logger()

    logger.debug('[TEST-LIBSALT] DEBUG LOGs >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
    logger.debug("The SALT Scenario File: {}".format(salt_cfg))

    # 1. Start the SALT
    libsalt.start(salt_cfg)

    # TODO: 2. Check the Begin & End of the simulation
    step = 0

    # 3. Define the target Traffic Signal
    # targetTLNode = "cluster_572701114_572701116_572701117_572712746_572712755"   # For Gandong-gu, Seoul
    targetTLNode = "cluster_563103641_563103889_563103894_563103895"  # For Doan, Daejeon

    # 4. Get the Traffic Signal Information (e.g. schdules)  using get function
    tl = libsalt.trafficsignal.getTLSByNodeID(targetTLNode)

    logger.debug("[Connected Link IDs] {} ".format(
        libsalt.trafficsignal.getTLSConnectedLinkID(targetTLNode)))

    logger.debug("[Target Traffic Signal ID] {}".format(tl.myTLSID))
    logger.debug(
        "The Number of schedules in the target traffic signal: {}".format(
            tl.getScheduleMap().size()))
    tsm = tl.getScheduleMap()

    if logger.isEnabledFor(logging.DEBUG):
        logger.debug(
            "The Schedule IDs in the target traffic signal: {}".format(
                tsm.keys()))
        logger.debug("The Schedule Detailed >>>>>> ")
        for k in tsm.keys():
            logger.debug("[schedule id: {}]".format(k))
            for p in tsm[k].getPhaseVector():
                logger.debug("phase = ({}), duration = {}".format(p[0], p[1]))

        logger.debug("The Phase Vector in Schedule {}  >>>>>>>>>>>>>>".format(
            tsm.keys()[0]))
        tsps = libsalt.trafficsignal.getTLSPhasesByNodeID(
            targetTLNode,
            tsm.keys()[0])
        for pp in tsps:
            logger.debug("({}, {})".format(pp[0], pp[1]))

        logger.debug("The Phase Index {}".format(3))
        tp = libsalt.trafficsignal.getTLSPhaseByNodeID(targetTLNode,
                                                       tsm.keys()[0], 3)
        logger.debug("({}, {})".format(tp[0], tp[1]))

    # 5. Testing setTLS
    # >>> 1) define the test scenario
    # >>> 2) test the setTLS & show results
    # >>> [test example] add 1 time step to a duration time of the intermediate phase (e.g. yellow phase) in the 1st schedule of the target TLS
    newsch = libsalt.TLSSchedulesMap()
    for k in enumerate(tsm.keys()):
        if k[0] == 0:
            newpv = libsalt.TLSPhaseVector()
            for p in tsm[k[1]].getPhaseVector():
                if p[0] < 5:
                    newp = libsalt.TLSPhasePair((p[0] + 1, p[1]))
                    newpv.append(newp)
                else:
                    orip = libsalt.TLSPhasePair(p)
                    newpv.append(orip)
            if logger.isEnabledFor(logging.DEBUG):
                logger.debug("The number of Phases: {} ".format(newpv.size()))
                logger.debug("(phases) >>>>>>>>>>>> ")
                for pv in newpv:
                    logger.debug(pv)
            newschedule = libsalt.TLSSchedule(tsm[k[1]].getSchedulID(),
                                              tsm[k[1]].getOffset(), newpv)
            if logger.isEnabledFor(logging.DEBUG):
                logger.debug("[DEBUG] new libsalt.TLSSchedule ")
                logger.debug("(offset): ".format(newschedule.getOffset()))
                logger.debug("(phases) >>>>>>>>>>>>>")
                for pv in newschedule.getPhaseVector():
                    logger.debug(pv)
            newsch[k[1]] = newschedule
        else:
            newpv2 = libsalt.TLSPhaseVector()
            for p2 in tsm[k[1]].getPhaseVector():
                orip2 = libsalt.TLSPhasePair(p2)
                newpv2.append(orip2)
            newschedule2 = libsalt.TLSSchedule(tsm[k[1]].getSchedulID(),
                                               tsm[k[1]].getOffset(), newpv2)
            newsch[k[1]] = newschedule2
            if logger.isEnabledFor(logging.DEBUG):
                logger.debug("[DEBUG] new libsalt.TLSSchedule ")
                logger.debug("(offset): ".format(newschedule2.getOffset()))
                logger.debug("(phases) >>>>>>>>>>>>>")
                for pv in newschedule2.getPhaseVector():
                    logger.debug(pv)

        if logger.isEnabledFor(logging.DEBUG):
            logger.debug(
                "[DEBUG] New TLSSchedule for 'set' information  >>>>>>>>>>>>>>>>>>"
            )
            for k in newsch.keys():
                logger.debug("[schedule id: {}]".format(k))
                for p in newsch[k].getPhaseVector():
                    logger.debug("phase = ({}), duration = {}".format(
                        p[0], p[1]))

    tod = tl.getTODPlan()
    newtod = libsalt.TLSTODMap()
    for k in tod.keys():
        newtod[k] = tod[k]

    newtl = libsalt.TLSLogic(targetTLNode, newsch, newtod)
    logger.debug("Schedule IDs (for setTLS test): {}".format(
        newtl.getScheduleMap().keys()))
    res = libsalt.trafficsignal.setTLSByNodeID(targetTLNode, newtl)
    logger.debug(res)
def test_computeWaitingVehInfo(salt_cfg):
    logger = __get_logger()

    logger.debug('[TEST-LIBSALT] DEBUG LOGs >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
    logger.debug("The SALT Scenario File: {}".format(salt_cfg))

    # 1. Start the SALT
    libsalt.start(salt_cfg)

    # TODO: 2. Check the Begin & End of the simulation
    step = 0

    # 3. Define the target Traffic Signal --> ex: Gildong-4
    # targetTLNode = "cluster_572701114_572701116_572701117_572712746_572712755"   # For Gandong-gu, Seoul
    targetTLNode = "cluster_563103641_563103889_563103894_563103895"  # For Doan, Daejeon

    # 4. Get the Traffic Signal Information (e.g. schdules)  using get function
    tl = libsalt.trafficsignal.getTLSByNodeID(targetTLNode)

    conlinkset = libsalt.trafficsignal.getTLSConnectedLinkID(targetTLNode)

    logger.debug("[Connected Link IDs] {} ".format(
        libsalt.trafficsignal.getTLSConnectedLinkID(targetTLNode)))
    logger.debug("[Target Traffic Signal ID] {}".format(tl.myTLSID))
    logger.debug(
        "The Number of schedules in the target traffic signal: {}".format(
            tl.getScheduleMap().size()))

    tsm = tl.getScheduleMap()

    logger.debug("The Schedule IDs in the target traffic signal: {}".format(
        tsm.keys()))
    logger.debug("The Schedule Detailed >>>>>> ")

    if logger.isEnabledFor(logging.DEBUG):
        for k in tsm.keys():
            logger.debug("[schedule id: {}]".format(k))
            for p in tsm[k].getPhaseVector():
                logger.debug("phase = ({}), duration = {}".format(p[0], p[1]))
        logger.debug("The Phase Vector in Schedule {}  >>>>>>>>>>>>>>".format(
            tsm.keys()[0]))
        tsps = libsalt.trafficsignal.getTLSPhasesByNodeID(
            targetTLNode,
            tsm.keys()[0])
        for pp in tsps:
            logger.debug("({}, {})".format(pp[0], pp[1]))
        logger.debug("The Phase Index {}".format(3))
        tp = libsalt.trafficsignal.getTLSPhaseByNodeID(targetTLNode,
                                                       tsm.keys()[0], 3)
        logger.debug("({}, {})".format(tp[0], tp[1]))

    # 5. Test Scenario
    # >>> 1) define changing rule (e.g. changing order, testing scenarios)
    # >>> 2) test the changeTLPhase function & show results
    # >>> [test example] every 30 step, changing the phase to next (skip the yellow or all red phase for transition of TLS)
    triggerduration = 1000
    computeduration = 30
    orderdic = {}
    turn = 0
    for k in tsm.keys():
        for p in enumerate(tsm[k].getPhaseVector()):
            if p[1][0] > 5:
                pair = []
                pair.append(k)
                pair.append(p[0])
                orderdic[turn] = pair
                turn += 1
    logger.debug("The order of phases: {}".format(orderdic))

    while step <= libsalt.getEndStep():
        curstep = libsalt.getCurrentStep()
        begin = libsalt.getBeginStep()

        if (curstep % triggerduration) == 0:
            ordering = (curstep / triggerduration) % len(orderdic)
            curscheduleid = orderdic[ordering][0]
            curphaseindex = orderdic[ordering][1]
            if logger.isEnabledFor(logging.DEBUG):
                logger.debug(
                    "Ordering: {}, current ts schedule id: {}, , current ts phase index: {}"
                    .format(ordering, curscheduleid, curphaseindex))
                logger.debug(
                    "[Trigger Point] time: {}, schdule id: {}  ({})".format(
                        curstep,
                        libsalt.trafficsignal.getCurrentTLSScheduleIDByNodeID(
                            targetTLNode),
                        libsalt.trafficsignal.getCurrentTLSPhaseStateByNodeID(
                            targetTLNode)))
            libsalt.trafficsignal.changeTLSPhase(curstep, targetTLNode,
                                                 curscheduleid, curphaseindex)
            if logger.isEnabledFor(logging.DEBUG):
                logger.debug("[After Changing] schedule id : {} ({})".format(
                    libsalt.trafficsignal.getCurrentTLSScheduleIDByNodeID(
                        targetTLNode),
                    libsalt.trafficsignal.getCurrentTLSPhaseStateByNodeID(
                        targetTLNode)))

        libsalt.simulationStep()

        if ((curstep % computeduration) == computeduration -
                1) and (curstep > begin + computeduration):
            lastswitching = libsalt.trafficsignal.getLastTLSPhaseSwitchingTimeByNodeID(
                targetTLNode)
            if logger.isEnabledFor(logging.DEBUG):
                logger.debug(
                    "Last Switching Time: {}, current Step: {}".format(
                        lastswitching, curstep))
                logger.debug("[Traget Signal {} ] ".format(targetTLNode))
                for li in conlinkset:
                    logger.debug(
                        "[link: {}] NumWaitVeh: {}, Average veh waiting time: {}, Average veh waiting Q length: {} "
                        .format(
                            li,
                            libsalt.link.getNumWaitingVehicle(
                                li, curstep, lastswitching),
                            libsalt.link.getAverageVehicleWaitingTime(
                                li, curstep, lastswitching),
                            libsalt.link.getAverageVehicleWaitingQLength(
                                li, curstep, lastswitching)))

        step += 1

    libsalt.close()
    logger.debug("simulation end!!!")
def main():
    args = parse_args()
    confPath = os.path.join(cwd_path, args.conf)
    scenarioPath = os.path.join(cwd_path, args.scenario)
    output_path = os.path.join(default_output_path, args.optimID)

    beginStep = args.beginStep
    endStep = args.endStep
    epochs = args.epochs

    targetTLNode = args.targetTL
    optimID = args.optimID

    output_filename_reward = os.path.join(default_output_path, args.optimID,
                                          "output-reward.csv")
    output_filename_phase_rl = os.path.join(default_output_path, args.optimID,
                                            "output-phase-rl.csv")
    output_filename_phase_ft = os.path.join(default_output_path, args.optimID,
                                            "output-phase-ft.csv")
    output_dir = s.path.join(default_output_path, args.optimID)
    model_dir = os.path.join(default_model_path, args.optimID)
    Path(output_dir).mkdir(parents=True, exist_ok=True)
    Path(model_dir).mkdir(parents=True, exist_ok=True)

    # print('args', args)
    # print('conf path', confPath)
    # print('scenario path', scenarioPath)

    # ======================================

    action_space_size = 15  # (0-14)
    agent = Learner(action_space_size, 1, '1d')

    in_link_list = ['-563104367', '-563104373', '-563105308']
    out_link_list = ['563104367', '563104373', '563105308']

    if args.mode == 'train':
        with open(output_filename_reward, 'w+') as f:
            f.write("Simulation,reward_sum\n")
        for simulation in range(epochs):
            libsalt.start(scenarioPath)
            libsalt.setCurrentStep(beginStep)
            step = libsalt.getCurrentStep()
            total_reward = 0
            link_list = libsalt.trafficsignal.getTLSConnectedLinkID(
                targetTLNode)
            current_phase = libsalt.trafficsignal.getCurrentTLSPhaseIndexByNodeID(
                targetTLNode)
            current_schedule_id = libsalt.trafficsignal.getCurrentTLSScheduleIDByNodeID(
                targetTLNode)

            print("cycle init start")
            for i in phase_num:
                while True:
                    current_phase = libsalt.trafficsignal.getCurrentTLSPhaseIndexByNodeID(
                        targetTLNode)
                    if current_phase != i:
                        break
                    current_schedule_id = libsalt.trafficsignal.getCurrentTLSScheduleIDByNodeID(
                        targetTLNode)
                    libsalt.simulationStep()
                    step = libsalt.getCurrentStep()
                    # print("step {} current_phase {}".format(simulationSteps, current_phase))
            print("cycle init end")

            done = 0
            cycle_idx = 0
            while step <= endStep:
                state = get_state_1d_v2(targetTLNode)
                action = agent.act(state)

                p1_duration = min_green[0] + action * 2  # (26-54)
                p2_duration = cycle - p1_duration  # (94-66)

                phase_arr = [p1_duration, p2_duration]

                reward_list = []
                for idx, duration in enumerate(phase_arr):
                    for i in range(duration):
                        libsalt.trafficsignal.changeTLSPhase(
                            step, targetTLNode, current_schedule_id, idx)
                        libsalt.simulationStep()
                        step = libsalt.getCurrentStep()
                        reward_tmp = getReward(in_link_list, out_link_list)
                        reward_list = np.append(reward_list, reward_tmp)

                reward = np.mean(reward_list)  # + p2_duration*0.1
                reward = np.round(reward, 2)
                # print(reward)
                total_reward += reward

                next_state = get_state_1d_v2(targetTLNode)

                agent.remember(state, action, reward, next_state, done)

                if cycle_idx % 8 == 0 and agent.batch_size < len(agent.memory):
                    agent.increase_target_update_counter()
                    agent.replay()
                cycle_idx += 1

            libsalt.close()

            with open(output_filename_reward, "a") as f:
                f.write("{},{}\n".format(simulation, np.round(total_reward,
                                                              2)))
                model_path = os.path.join(model_dir,
                                          "traffic_epoch{}".format(simulation))
                agent.save(model_path)

            print("Python: Simulation End!!!")
        print("Python: Training End!!!")

    elif args.mode == 'test':
        agent = Learner(action_space_size, 0, '1d')

        libsalt.start(scenarioPath)
        libsalt.setCurrentStep(beginStep)
        step = libsalt.getCurrentStep()
        total_reward = 0
        link_list = libsalt.trafficsignal.getTLSConnectedLinkID(targetTLNode)
        current_phase = libsalt.trafficsignal.getCurrentTLSPhaseIndexByNodeID(
            targetTLNode)
        current_schedule_id = libsalt.trafficsignal.getCurrentTLSScheduleIDByNodeID(
            targetTLNode)

        print("cycle init start")
        for i in phase_num:
            while True:
                current_phase = libsalt.trafficsignal.getCurrentTLSPhaseIndexByNodeID(
                    targetTLNode)
                if current_phase != i:
                    break
                current_schedule_id = libsalt.trafficsignal.getCurrentTLSScheduleIDByNodeID(
                    targetTLNode)
                libsalt.simulationStep()
                step = libsalt.getCurrentStep()
                # print("step {} current_phase {}".format(simulationSteps, current_phase))
        print("cycle init end")

        with open(output_filename_phase_rl, "w+") as f:
            f.write("SimulationStep,action,p1_duration,p2_duration\n")

        model_num = args.model_num
        trained_model_path = os.path.join(model_dir,
                                          "traffic_epoch{}".format(model_num))
        print(trained_model_path)
        agent.load(trained_model_path)

        done = 0
        cycle_idx = 0
        while step <= endStep:
            state = get_state_1d_v2(targetTLNode)
            action = agent.act(state)

            p1_duration = min_green[0] + action * 2  # (26-54)
            p2_duration = cycle - p1_duration  # (94-66)

            phase_arr = [p1_duration, p2_duration]

            with open(output_filename_phase_rl, "a") as f:
                f.write("{},{},{},{}\n".format(step, action, p1_duration,
                                               p2_duration))

            reward_list = []
            for idx, duration in enumerate(phase_arr):
                for i in range(duration):
                    libsalt.trafficsignal.changeTLSPhase(
                        step, targetTLNode, current_schedule_id, idx)
                    libsalt.simulationStep()
                    step = libsalt.getCurrentStep()
                    reward_tmp = getReward(in_link_list, out_link_list)
                    reward_list = np.append(reward_list, reward_tmp)

            reward = np.mean(reward_list)  # + p2_duration*0.1
            reward = np.round(reward, 2)
            # print(reward)
            total_reward += reward

        libsalt.close()
        print("Python: Simulation End!!!")
    # ======================================

    elif args.mode == 'fixed':
        libsalt.start(scenarioPath)
        libsalt.setCurrentStep(beginStep)
        step = libsalt.getCurrentStep()
        link_list = libsalt.trafficsignal.getTLSConnectedLinkID(targetTLNode)
        current_phase = libsalt.trafficsignal.getCurrentTLSPhaseIndexByNodeID(
            targetTLNode)

        print("cycle init start")
        for i in phase_num:
            while True:
                current_phase = libsalt.trafficsignal.getCurrentTLSPhaseIndexByNodeID(
                    targetTLNode)
                if current_phase != i:
                    break
                current_schedule_id = libsalt.trafficsignal.getCurrentTLSScheduleIDByNodeID(
                    targetTLNode)
                libsalt.simulationStep()
                step = libsalt.getCurrentStep()
                #print("step {} current_phase {}".format(step, current_phase))
        print("cycle init end")

        with open(output_filename_phase_ft, "w+") as f:
            f.write("SimulationStep,p1_duration,p2_duration\n")

        while step <= endStep:
            p1_duration = 35
            p2_duration = 85

            phase_arr = [p1_duration, p2_duration]

            with open(output_filename_phase_ft, "a") as f:
                f.write("{},{},{}\n".format(step, p1_duration, p2_duration))

            for idx, duration in enumerate(phase_arr):
                for i in range(duration):
                    current_schedule_id = libsalt.trafficsignal.getCurrentTLSScheduleIDByNodeID(
                        targetTLNode)
                    # libsalt.trafficsignal.changeTLSPhase(simulationSteps, targetTLNode, current_schedule_id, 1)
                    current_phase = libsalt.trafficsignal.getCurrentTLSPhaseIndexByNodeID(
                        targetTLNode)
                    print("step {} current_phase {}".format(
                        step, current_phase))
                    libsalt.simulationStep()
                    step = libsalt.getCurrentStep()

        libsalt.close()

    exit(0)
def main():
    args = parse_args()
    confPath = os.path.join(cwd_path, args.conf)
    scenarioPath = os.path.join(cwd_path, args.scenario)
    print('args', args)
    print('conf path', confPath)
    print('scenario path', scenarioPath)

    #confJson = getJsonObj(confPath)
    #print('conf json', confJson)
    scenarioJson = getJsonObj(scenarioPath)
    #print('scenario json', scenarioJson)
    beginStep = scenarioJson['scenario']['time']['begin']
    endStep = scenarioJson['scenario']['time']['end']

    scenarios = []

    libsalt.start(scenarioPath)
    libsalt.setCurrentStep(beginStep)
    step = libsalt.getCurrentStep()

    logger = __get_logger()

    # 3. Define the target Traffic Signal
    targetTLNode = "cluster_563101055_563101057_563101523_563101524_563101565_563101566"


    # 4. Get the Traffic Signal Information (e.g. schdules)  using get function
    tl = libsalt.trafficsignal.getTLSByNodeID(targetTLNode)
    conlinkset = libsalt.trafficsignal.getTLSConnectedLinkID(targetTLNode)

    triggerduration = 120

    while step <= endStep:
        libsalt.simulationStep()
        step = libsalt.getCurrentStep()

        curstep = libsalt.getCurrentStep()
        begin = libsalt.getBeginStep()

        if (curstep % triggerduration)==0:
            if logger.isEnabledFor(logging.DEBUG):
                print('The State of Waiting Vehicles Over TLS Duration at {}:'.format(targetTLNode))

                for conl in conlinkset:
                    lanelist = libsalt.link.getLaneList(conl)
                    for lnc in lanelist:
                        lane = lnc.toString()
                        print('[Connected Link: {} Lane: {}]: state = {}, avg_wt = {}, sum_wt = {}'.format(
                            conl, lane, libsalt.lane.getStateOfWaitingVehicleOverTLSDuration(lane, curstep),
                            libsalt.lane.getCurrentAverageWaitingTimeBaseVehicle(lane, curstep),
                            libsalt.lane.getCurrentWaitingTimeSumBaseVehicle(lane, curstep)))

                    print('[Connected Link {}] state = {}, avg_wt = {}, sum_wt = {}'.format(
                        conl, libsalt.link.getStateOfWaitingVehicleOverTLSDuration(conl, curstep),
                        libsalt.link.getCurrentAverageWaitingTimeBaseVehicle(conl, curstep),
                        libsalt.link.getCurrentWaitingTimeSumBaseVehicle(conl, curstep)))

    libsalt.close()
    print("Python: Simulation First End!!!")

    exit(0)