Esempio n. 1
0
def run():
    random.seed(1)
    randomLambda = random.Random(1)
    randomPackages = random.Random(1)
    print("RUN")
    print(strategy)
    simulation = Simulation(step=0,
                            threshold_L=threshold_L,
                            threshold_H=threshold_H,
                            k=1,
                            control_area_edges=control_area_edges_cnf)
    window = Window(simulation.step, set(), set(), 0, 0, 0, 0, 0, 1, 0.5, 0.8)

    if (strategy != "baseline" and strategy not in not_strategy):
        openHistorical(simulation)

    while traci.simulation.getMinExpectedNumber(
    ) > 0:  # While there are cars (and waiting cars)
        # LAST STEP
        # Vehicles to control area
        vehs_load = traci.simulation.getLoadedIDList()
        vehs_load_Vehicle = []
        for veh in vehs_load:
            if veh != "simulation.findRoute":
                vehicl = Vehicle(veh)
                vehs_load_Vehicle.append(vehicl)

        simulation.vehs_load = vehs_load_Vehicle
        update_vehicles_to_control_area(simulation)

        if simulation.step == 0:
            simulation.NOx_control_zone_restriction_mode = p_t_ini
            simulation.p_t = simulation.NOx_control_zone_restriction_mode
            window.NOx_total_w = p_t_ini
            window.NOx_control_zone_w = p_t_ini
            window.p_t = p_t_ini
            window.p_t_total = p_t_ini
            window.lambda_l = 0.8
            window.alpha = alpha_ini
            simulation.add_alpha(alpha_ini)
            #print("STEP 0", simulation.alphas)
            #print(simulation.alphas[len(simulation.alphas) - 1])

            # Add variables for the last 50 steps
            simulation.add_window(window)
            print("Window: ", window)

            # Reboot all
            window = Window(simulation.step, window.vehicles_in_w.copy(),
                            set(), 0, 0, window.veh_total_number_w)

            # NEW STEP
        traci.simulationStep()  # Advance one time step: one second
        simulation.update_Step()
        window.update_Step()

        # MANAGE VEHICLES - All simulation
        id_vehs_departed = list(
            traci.simulation.getDepartedIDList())  # Vehicles in simulation

        if (id_vehs_departed):  # if the list is not empty
            # All simulation:
            id_vehs_departed_Vehicle = []
            for id_veh_dep in id_vehs_departed:
                if id_veh_dep != "simulation.findRoute":
                    id_veh_dep_Vehicle = Vehicle(id_veh_dep)
                    id_veh_dep_Vehicle.step_ini = simulation.step
                    num_packages = randomPackages.randint(
                        min_packages, max_packages)
                    id_veh_dep_Vehicle.n_packages = num_packages
                    id_veh_dep_Vehicle.vType = traci.vehicle.getTypeID(
                        id_veh_dep_Vehicle.id)
                    id_vehs_departed_Vehicle.append(id_veh_dep_Vehicle)
            simulation.add_vehicles_in_simulation(
                id_vehs_departed_Vehicle
            )  # Add vehicles to the simulation list
            simulation.add_all_veh(id_vehs_departed_Vehicle)
            # Per window:
            window.add_vehicles_in_w(simulation.vehicles_in_simulation)
            window.veh_total_number_w = len(window.vehicles_in_w)

        # Taking into account the vehicles that reach their destination:
        id_vehicles_arrived = traci.simulation.getArrivedIDList()
        for veh in id_vehicles_arrived:
            for veh_sim in simulation.vehicles_in_simulation:
                if veh == veh_sim.id:  # If the vehicle has arrived then remove it from the simulation
                    simulation.update_step_fin_veh(simulation.step, veh_sim)
                    simulation.remove_vehicles_in_simulation(veh_sim)
                    simulation.add_veh_total_number(
                        1)  # Update Vehicle Total Number in all simulation
                    for veh_w in window.vehicles_in_w:
                        if veh == veh_w.id:
                            window.remove_vehicles_in_w(veh_w)
                            window.sub_veh_total_number_w(1)
                            break
                    break

        ## IMPORTANT PART - FOR EACH VEHICLE:
        for veh in simulation.vehicles_in_simulation:
            # Emissions:
            # All simulation
            vehNOxEmission = traci.vehicle.getNOxEmission(
                veh.id)  # Return the NOx value per vehicle in each step

            if (strategy == "historical_VE" or strategy == "historical_VEP"):
                if vehNOxEmission > 0 and veh.id in historical_veh_acum:  # HISTORICAL
                    historical_veh_acum_contador[veh.id] += 1
                    historical_veh_acum[veh.id] += vehNOxEmission
                elif veh.id not in historical_veh_acum:
                    historical_veh_acum_contador[veh.id] = 1
                    historical_veh_acum[veh.id] = vehNOxEmission

            simulation.add_NOx_Total(vehNOxEmission)
            veh.add_NOx(vehNOxEmission)
            #print(veh.id, veh.NOx)
            # Per Window
            window.add_NOx_Total_w(vehNOxEmission)

            # Control Area:
            pos = traci.vehicle.getPosition(vehID=veh.id)  # (x,y)

            if (pos[1] <= min_y and pos[1] >= max_y) and (
                    pos[0] >= min_x and pos[0] <= max_x
            ):  # x=> 0, y=>1. If the vehicle is in the control area
                # All simulation:
                simulation.add_NOx_control_zone(vehNOxEmission)
                # Per window:
                window.add_NOx_control_zone_w(vehNOxEmission)
                # Control area:
                simulation.add_NOx_control_zone_restriction_mode(
                    vehNOxEmission)
                veh.enter_cz = True

            # Route lenght per vehicle
            rouIndex = traci.vehicle.getRouteIndex(veh.id)
            edges = traci.vehicle.getRoute(veh.id)

            if veh not in window.vehicles_in_control_zone_w and edges[
                    rouIndex] + "_0" in control_area_edges_cnf:
                window.add_vehicles_in_control_zone_w(veh.id)
            """
            if rouIndex == (len(edges) - 1):  # Only if is the last edge
                stage = traci.simulation.findRoute(edges[0], edges[rouIndex])
                rouLength = stage.length  # Route Length
                veh.total_km = rouLength
            """

            # Control area - Threshold:
            try:
                """
                if strategy == "historical":
                    # NOTHING TO DO
                """
                if strategy == "baseline":
                    class_veh_changer_baseline(simulation, veh)
                elif strategy == "VE" or strategy == "VEP":
                    class_veh_changer_VE_OR_VEP(simulation, veh)
                elif strategy == "RRE" or strategy == "RREP":
                    class_veh_changer_RRE_OR_RREP(simulation, veh)
            except NameError:
                print("Strategy doesn't found")
                # REROUTE VEHICLES:
            #if rouIndex != (len(edges) - 1) and edges[rouIndex+1]+"_0" in control_area_edges_cnf:
            if strategy not in not_strategy:
                traci.vehicle.rerouteTraveltime(veh.id, True)

        # Window
        if ((simulation.step % window_size) == 0):
            # Discount NOx of the last window:
            for w in range(len(simulation.windows)):
                if simulation.windows[w].step == simulation.step - window_size:
                    lambda_l = randomLambda.uniform(0.8, 1.2)

                    alpha = max(
                        0.5,
                        min(
                            1, lambda_l *
                            simulation.alphas[len(simulation.alphas) - 1]))
                    simulation.add_alpha(alpha)

                    window.lambda_l = lambda_l
                    window.alpha = alpha
                    """
                    p_t = alpha * simulation.windows[w].p_t + window.NOx_control_zone_w
                    p_t_total = alpha * simulation.windows[w].p_t_total + window.NOx_total_w
                    """

                    x_cz = lambda_l * subs_NOx
                    p_t = max(
                        0, simulation.windows[w].p_t +
                        window.NOx_control_zone_w - x_cz)

                    y_total = x_cz * size_ratio
                    p_t_total = max(
                        0, simulation.windows[w].p_t_total +
                        window.NOx_total_w - y_total)

                    simulation.NOx_control_zone_restriction_mode = p_t
                    simulation.p_t = p_t

                    window.p_t = p_t
                    window.p_t_total = p_t_total

                    if simulation.p_t < 0:
                        simulation.NOx_control_zone_restriction_mode = 0
                        simulation.p_t = 0
                        window.p_t = 0

            # Add variables for the last 50 steps
            simulation.add_window(window)
            print("Window: ", window)

            # Reboot all

            window = Window(simulation.step, window.vehicles_in_w.copy(),
                            window.vehicles_in_control_zone_w.copy(), 0, 0,
                            window.veh_total_number_w)
            window.vehicles_in_control_zone_w = set()

            # CONTROL ZONE
            decision_maker(simulation, window)

        #print(simulation.step, "NOx_control_zone: ", simulation.NOx_control_zone, ". NOx_control_zone_restriction_mode: ", simulation.NOx_control_zone_restriction_mode, ". NOx_total: ", simulation.NOx_total)

    minutes = round(simulation.step / 60, 0)
    """
    for v in simulation.all_veh:
        simulation.total_kilometers += v.total_km
    """

    ## RESULTS FILE 2
    cont_file = 0
    file = "results_file_"
    fileName = r"./results/" + file + str(cont_file) + ".csv"
    print(fileName)
    fileObject = Path(fileName)
    while fileObject.is_file():
        cont_file += 1
        fileName = r"./results/" + file + str(cont_file) + ".csv"
        print(fileName)
        fileObject = Path(fileName)
    f = open(fileName, "w")

    # Results:

    f.write(strategy + "\n")
    f.write("PARAMETERS," + "\n")
    f.write(
        "window_size, threshold_L, threshold_H, alpha_ini, p_t_ini, min_packages, max_packages,"
        + "\n")
    f.write(
        str(window_size) + "," + str(threshold_L) + "," + str(threshold_H) +
        "," + str(alpha_ini) + "," + str(p_t_ini) + "," + str(min_packages) +
        "," + str(max_packages) + "," + "\n")
    f.write("WINDOWS," + "\n")
    f.write(
        "step, NOx_total_w, NOx_total_acum, alpha, lambda, p_t_total, e_t_total, p_t_control_zone, e_t_control_zone, k_control_zone, num_veh_total, num_vehicles_control_zone,  "
        + "\n")

    acum = 0
    for w in simulation.windows:
        acum += w.NOx_total_w
        f.write(
            str(w.step) + "," + str(w.NOx_total_w) + "," + str(acum) + "," +
            str(w.alpha) + "," + str(w.lambda_l) + "," + str(w.p_t_total) +
            "," + str(w.NOx_total_w) + "," + str(w.p_t) + "," +
            str(w.NOx_control_zone_w) + "," + str(w.k) + "," +
            str(w.veh_total_number_w) + "," +
            str(len(w.vehicles_in_control_zone_w)) + "," + "\n")

    f.write("VEHICLES," + "\n")
    f.write(
        "id, vType, NOx_total_veh, n_packages, step_ini, step_fin, total_time(sec),average_package,enter_cz,"
        + "\n")

    p_all = 0
    cont = 0
    avg_contrib = 0
    total_packages = 0

    def sortFunc(v):
        return v.step_ini

    simulation.all_veh = sorted(simulation.all_veh, key=sortFunc)

    for v in simulation.all_veh:
        total_time = v.step_fin - v.step_ini
        average_package = total_time / v.n_packages
        p_all += average_package
        cont += 1
        avg_contrib += total_time * v.n_packages
        total_packages += v.n_packages

        f.write(v.id + "," + v.vType + "," + str(v.NOx) + "," +
                str(v.n_packages) + "," + str(v.step_ini) + "," +
                str(v.step_fin) + "," + str(total_time) + "," +
                str(average_package) + "," + str(v.enter_cz) + "," + "\n")

    average_package_all = avg_contrib / total_packages
    f.write("ALL SIMULATION," + "\n")
    f.write("total_steps(sec), minutes, avg_package_all_sim," + "\n")
    f.write(
        str(simulation.step) + "," + str(minutes) + "," +
        str(average_package_all) + "," + "\n")

    f.close()

    ## HISTORICAL
    if strategy == "historical_VE" or strategy == "historical_VEP":
        ## HISTORICAL
        for veh in simulation.all_veh:
            historical_veh_acum[veh.id] = historical_veh_acum[
                veh.id] / historical_veh_acum_contador[veh.id]
            if strategy == "historical_VEP":
                historical_veh_acum[
                    veh.id] = historical_veh_acum[veh.id] / veh.n_packages
        hist_veh = dict(
            sorted(historical_veh_acum.items(),
                   key=lambda item: item[1]))  # sort

        # RESULTS FILE - HISTORICAL
        cont_file = 0
        if strategy == "historical_VE":
            file = "historical_VE_"
            fileName = r"./historical_VE_results/" + file + str(
                cont_file) + ".txt"
            print(fileName)
            fileObject = Path(fileName)
            while fileObject.is_file():
                cont_file += 1
                fileName = r"./historical_VE_results/" + file + str(
                    cont_file) + ".txt"
                print(fileName)
                fileObject = Path(fileName)
        elif strategy == "historical_VEP":
            file = "historical_VEP_"
            fileName = r"./historical_VEP_results/" + file + str(
                cont_file) + ".txt"
            print(fileName)
            fileObject = Path(fileName)
            while fileObject.is_file():
                cont_file += 1
                fileName = r"./historical_VEP_results/" + file + str(
                    cont_file) + ".txt"
                print(fileName)
                fileObject = Path(fileName)
        # f=open("./"+fileName+".txt", "w")
        f = open(fileName, "w")

        for k, v in hist_veh.items():
            f.write(k + " " + str(v) + "\n")

        f.close()

    # TraCI
    traci.close()
    sys.stdout.flush()
Esempio n. 2
0
def run():
    random.seed(1)
    print("RUN")
    simulation = Simulation(step=0,
                            threshold=threshold_size,
                            control_area_edges=control_area_edges_cnf)
    window = Window(simulation.step, set(), set(), 0, 0, 0)

    while traci.simulation.getMinExpectedNumber(
    ) > 0:  # While there are cars (and waiting cars)
        # LAST STEP
        # Vehicles to control area
        vehs_load = traci.simulation.getLoadedIDList()
        vehs_load_Vehicle = []
        for veh in vehs_load:
            if veh != "simulation.findRoute":
                vehicl = Vehicle(veh)
                vehs_load_Vehicle.append(vehicl)

        simulation.vehs_load = vehs_load_Vehicle
        update_vehicles_to_control_area(simulation)

        if simulation.step == 0:
            simulation.NOx_control_zone_restriction_mode = p_t_ini
            window.NOx_total_w = p_t_ini
            window.NOx_control_zone_w = p_t_ini
            window.p_t = p_t_ini
            window.p_t_total = p_t_ini
            window.lambda_l = 0.8
            window.alpha = alpha_ini
            simulation.add_alpha(alpha_ini)
            #print("STEP 0", simulation.alphas)
            #print(simulation.alphas[len(simulation.alphas) - 1])

            # Add variables for the last 50 steps
            simulation.add_window(window)
            print("Window: ", window)

            # Reboot all
            window = Window(simulation.step, window.vehicles_in_w.copy(),
                            set(), 0, 0, window.veh_total_number_w)

        # NEW STEP
        traci.simulationStep()  # Advance one time step: one second
        simulation.update_Step()
        window.update_Step()

        # MANAGE VEHICLES - All simulation
        id_vehs_departed = list(
            traci.simulation.getDepartedIDList())  # Vehicles in simulation

        if (id_vehs_departed):  # if the list is not empty
            # All simulation:
            id_vehs_departed_Vehicle = []
            for id_veh_dep in id_vehs_departed:
                if id_veh_dep != "simulation.findRoute":
                    id_veh_dep_Vehicle = Vehicle(id_veh_dep)
                    id_veh_dep_Vehicle.step_ini = simulation.step
                    num_packages = random.randint(min_packages, max_packages)
                    id_veh_dep_Vehicle.n_packages = num_packages
                    id_veh_dep_Vehicle.vType = traci.vehicle.getTypeID(
                        id_veh_dep_Vehicle.id)
                    id_vehs_departed_Vehicle.append(id_veh_dep_Vehicle)
            simulation.add_vehicles_in_simulation(
                id_vehs_departed_Vehicle
            )  # Add vehicles to the simulation list
            simulation.add_all_veh(id_vehs_departed_Vehicle)
            # Per window:
            window.add_vehicles_in_w(simulation.vehicles_in_simulation)
            window.veh_total_number_w = len(window.vehicles_in_w)

        # Taking into account the vehicles that reach their destination:
        id_vehicles_arrived = traci.simulation.getArrivedIDList()
        for veh in id_vehicles_arrived:
            for veh_sim in simulation.vehicles_in_simulation:
                if veh == veh_sim.id:  # If the vehicle has arrived then remove it from the simulation
                    simulation.update_step_fin_veh(simulation.step, veh_sim)
                    simulation.remove_vehicles_in_simulation(veh_sim)
                    simulation.add_veh_total_number(
                        1)  # Update Vehicle Total Number in all simulation
                    for veh_w in window.vehicles_in_w:
                        if veh == veh_w.id:
                            window.remove_vehicles_in_w(veh_w)
                            window.sub_veh_total_number_w(1)
                            break
                    break

        ## IMPORTANT PART - FOR EACH VEHICLE:
        for veh in simulation.vehicles_in_simulation:
            # Emissions:
            # All simulation
            vehNOxEmission = traci.vehicle.getNOxEmission(
                veh.id)  # Return the NOx value per vehicle in each step

            if vehNOxEmission > 0 and veh.id in historical_veh_max:  #HISTORICAL
                historical_veh_max_contador[veh.id] += 1
                historical_veh_max[veh.id] += vehNOxEmission
            elif veh.id not in historical_veh_max:
                historical_veh_max_contador[veh.id] = 1
                historical_veh_max[veh.id] = vehNOxEmission

            simulation.add_NOx_Total(vehNOxEmission)
            veh.add_NOx(vehNOxEmission)
            #print(veh.id, veh.NOx)
            # Per Window
            window.add_NOx_Total_w(vehNOxEmission)

            # Control Area:
            pos = traci.vehicle.getPosition(vehID=veh.id)  # (x,y)

            if (pos[1] <= min_y and pos[1] >= max_y) and (
                    pos[0] >= min_x and pos[0] <= max_x
            ):  # x=> 0, y=>1. If the vehicle is in the control area
                # All simulation:
                simulation.add_NOx_control_zone(vehNOxEmission)
                # Per window:
                window.add_NOx_control_zone_w(vehNOxEmission)
                # Control area:
                simulation.add_NOx_control_zone_restriction_mode(
                    vehNOxEmission)

            # Route lenght per vehicle
            rouIndex = traci.vehicle.getRouteIndex(veh.id)
            edges = traci.vehicle.getRoute(veh.id)
            if veh not in window.vehicles_in_control_zone_w and edges[
                    rouIndex] + "_0" in control_area_edges_cnf:
                window.add_vehicles_in_control_zone_w(veh.id)
            """
            if rouIndex == (len(edges) - 1):  # Only if is the last edge
                stage = traci.simulation.findRoute(edges[0], edges[rouIndex])
                rouLength = stage.length  # Route Length
                veh.total_km = rouLength

            # Control area - Threshold:
            string_current_edge = edges[rouIndex] + "_0"
            if simulation.restrictionMode and traci.vehicle.getVehicleClass(veh.id)!="authority":
                if (string_current_edge in simulation.control_area_edges):  #  current edge in control area
                    vClass_last2 = traci.vehicle.getVehicleClass(veh.id)
                    traci.vehicle.setType(vehID=veh.id, typeID="authority")
                    if (vClass_last2 != "passenger"):
                        traci.vehicle.setEmissionClass(veh.id, "zero")

                # REROUTE VEHICLES:
            if simulation.restrictionMode:
                inList = False
                for edg in edges:
                    edgStrng = edg + "_0"
                    if edgStrng in simulation.control_area_edges:
                        inList = True
                        break
                if inList:
                    traci.vehicle.rerouteTraveltime(veh.id, True)
            """
        # Window
        if ((simulation.step %
             window_size) == 0):  # Each window, window_size steps
            # Discount NOx of the last window:
            for w in range(len(simulation.windows)):
                if simulation.windows[
                        w].step == simulation.step - window_size:  # The last window
                    lambda_l = random.uniform(0.8, 1.2)

                    alpha = max(
                        0.5,
                        min(
                            1, lambda_l *
                            simulation.alphas[len(simulation.alphas) - 1]))
                    simulation.add_alpha(alpha)

                    window.lambda_l = lambda_l
                    window.alpha = alpha

                    p_t = alpha * simulation.windows[
                        w].p_t + window.NOx_control_zone_w
                    p_t_total = alpha * simulation.windows[
                        w].p_t_total + window.NOx_total_w

                    simulation.NOx_control_zone_restriction_mode = p_t
                    window.p_t = p_t
                    window.p_t_total = p_t_total

                    if simulation.NOx_control_zone_restriction_mode < 0:
                        simulation.NOx_control_zone_restriction_mode = 0
                        window.p_t = 0

            # Add variables for the last 50 steps
            simulation.add_window(window)
            print("Window: ", window)

            # Reboot all
            window = Window(simulation.step, window.vehicles_in_w.copy(),
                            window.vehicles_in_control_zone_w.copy(), 0, 0,
                            window.veh_total_number_w)
            window.vehicles_in_control_zone_w = set()
        """
        # CONTROL ZONE ON
        #print(simulation.step, simulation.NOx_control_zone_restriction_mode)
        if simulation.vehicles_in_simulation != [] and simulation.restrictionMode == False and simulation.NOx_control_zone_restriction_mode > threshold_size:
            print("CONTROL ZONE ON", simulation.NOx_control_zone_restriction_mode)
            simulation.restrictionMode = True

            for aEd in simulation.control_area_edges:
                traci.lane.setDisallowed(laneID=aEd, disallowedClasses=["passenger", "evehicle"])
                #print("disa ", traci.lane.getDisallowed(laneID=aEd))
                traci.lane.setAllowed(laneID=aEd, allowedClasses=["authority"])
                #print("alo ", traci.lane.getAllowed(laneID=aEd))

        # CONTROL ZONE OFF
        if (simulation.restrictionMode and simulation.NOx_control_zone_restriction_mode <= threshold_size):
            print("CONTROL ZONE OFF", simulation.NOx_control_zone_restriction_mode)
            simulation.restrictionMode = False
            for aEd in simulation.control_area_edges:
                traci.lane.setAllowed(laneID=aEd, allowedClasses=["authority", "passenger", "evehicle"])
            for veh in simulation.vehicles_in_simulation:
                traci.vehicle.rerouteTraveltime(veh.id, True)
        """

        #print(simulation.step, "NOx_control_zone: ", simulation.NOx_control_zone, ". NOx_control_zone_restriction_mode: ", simulation.NOx_control_zone_restriction_mode, ". NOx_total: ", simulation.NOx_total)

    minutes = round(simulation.step / 60, 3)
    """
    for v in simulation.all_veh:
        simulation.total_kilometers += v.total_km
    """

    # Results:
    print("Windows:")
    for w in simulation.windows:
        print(w)
    print("Vehicles:")

    print("In ", simulation.step, "seconds (", minutes, " minutes)")
    print("All simulation:")
    print(simulation)

    ## HISTORICAL
    for veh in simulation.all_veh:
        print(historical_veh_max[veh.id], historical_veh_max_contador[veh.id])
        historical_veh_max[veh.id] = historical_veh_max[
            veh.id] / historical_veh_max_contador[veh.id]
        print(historical_veh_max[veh.id])
    hist_veh = dict(
        sorted(historical_veh_max.items(), key=lambda item: item[1]))  # sort

    # RESULTS FILE - HISTORICAL
    cont_file = 0
    file = "historical_"
    fileName = r"./historical_results/" + file + str(cont_file) + "_max.txt"
    print(fileName)
    fileObject = Path(fileName)
    while fileObject.is_file():
        cont_file += 1
        fileName = r"./historical_results/" + file + str(
            cont_file) + "_max.txt"
        print(fileName)
        fileObject = Path(fileName)
    # f=open("./"+fileName+".txt", "w")
    f = open(fileName, "w")

    for k, v in hist_veh.items():
        f.write(k + " " + str(v) + "\n")

    f.close()

    ## RESULTS FILE 2
    cont_file = 0
    file = "results_file_"
    fileName = r"./results2/" + file + str(cont_file) + ".csv"
    print(fileName)
    fileObject = Path(fileName)
    while fileObject.is_file():
        cont_file += 1
        fileName = r"./results2/" + file + str(cont_file) + ".csv"
        print(fileName)
        fileObject = Path(fileName)
    f = open(fileName, "w")

    # Results:

    f.write("HISTORICAL - NO CONTROL ZONE, " + "\n")
    f.write("PARAMETERS," + "\n")

    # p(t)
    f.write("window_size, alpha_ini, p_t_ini, min_packages, max_packages," +
            "\n")
    f.write(
        str(window_size) + "," + str(alpha_ini) + "," + str(p_t_ini) + "," +
        str(min_packages) + "," + str(max_packages) + "," + "\n")
    f.write("WINDOWS," + "\n")
    f.write(
        "step, NOx_total_w, NOx_total_acum, alpha, lambda, p_t_total, e_t_total, p_t_control_zone, e_t_control_zone, num_veh_total, num_vehicles_control_zone,  "
        + "\n")

    acum = 0
    for w in simulation.windows:
        acum += w.NOx_total_w
        f.write(
            str(w.step) + "," + str(w.NOx_total_w) + "," + str(acum) + "," +
            str(w.alpha) + "," + str(w.lambda_l) + "," + str(w.p_t_total) +
            "," + str(w.NOx_total_w) + "," + str(w.p_t) + "," +
            str(w.NOx_control_zone_w) + "," + str(w.veh_total_number_w) + "," +
            str(len(w.vehicles_in_control_zone_w)) + "," + "\n")

    f.write("VEHICLES," + "\n")
    f.write(
        "id, vType, NOx_total_veh, n_packages, step_ini, step_fin, total_time(sec),median_package,"
        + "\n")

    p_all = 0
    cont = 0
    for v in simulation.all_veh:
        total_time = v.step_fin - v.step_ini
        median_package = total_time / v.n_packages
        p_all += median_package
        cont += 1

        f.write(v.id + "," + v.vType + "," + str(v.NOx) + "," +
                str(v.n_packages) + "," + str(v.step_ini) + "," +
                str(v.step_fin) + "," + str(total_time) + "," +
                str(median_package) + "," + "\n")

    median_package_all = p_all / cont
    f.write("ALL SIMULATION," + "\n")
    f.write("total_steps(sec), minutes, median_package_all_sim," + "\n")
    f.write(
        str(simulation.step) + "," + str(minutes) + "," +
        str(median_package_all) + "," + "\n")

    f.close()

    # TraCI
    traci.close()
    sys.stdout.flush()
Esempio n. 3
0
def run():
    random.seed(1)
    randomLambda = random.Random(1)
    randomPackages = random.Random(1)
    print("RUN")
    print(strategy)
    simulation = Simulation(step = 0, threshold_L = threshold_L, threshold_H= threshold_H, k = 1)
    window = Window(simulation.step,set(), set(), 0,  0, 0, 0, 0, 1, 0.8)

    #open history file if necessary
    if (strategy!="baseline" and strategy!="noControl"):
        openHistorical(simulation)

    #put the centre closed for not allowed cars
    for aEd in control_area_edges_cnf:
        traci.lane.setDisallowed(laneID=aEd, disallowedClasses=["custom1"])

    lastkSmaller1=True
    start_total=True
    start_control=True

    #MAIN LOOP FOR THE SIMULATION
    while traci.simulation.getMinExpectedNumber() > 0:  # While there are cars (and waiting cars)
        # LAST STEP
        # Vehicles to control area
        vehs_load = traci.simulation.getLoadedIDList()
        vehs_load_Vehicle = []
        for veh in vehs_load:
            if veh != "simulation.findRoute":
                vehicl = Vehicle(veh)
                vehs_load_Vehicle.append(vehicl)

        simulation.vehs_load = vehs_load_Vehicle

        #initialize
        if simulation.step == 0:
            simulation.p_t = p_t_ini
            window.NOx_total_w = 0
            window.NOx_control_zone_w = 0
            window.p_t = p_t_ini
            window.p_t_total=p_t_ini
            window.lambda_l = 0.8
            #window.alpha = alpha_ini
            #simulation.add_alpha(alpha_ini)

            # Add variables for the last 50 steps
            simulation.add_window(window)
            print("Window: ", window)
            # Reboot all
            window = Window(simulation.step, window.vehicles_in_w.copy(), set(), 0, 0, window.veh_total_number_w)

            #calculate k
            calculate_k(simulation,window)


            # NEW STEP

        traci.simulationStep()  # Advance one time step: one second
        simulation.update_Step()
        window.update_Step()

        # MANAGE VEHICLES - All simulation
        id_vehs_departed = list(traci.simulation.getDepartedIDList()) # Vehicles in simulation
        if(id_vehs_departed): # if the list is not empty
            # All simulation:
            id_vehs_departed_Vehicle = []
            for id_veh_dep in id_vehs_departed:
                if id_veh_dep != "simulation.findRoute":
                    id_veh_dep_Vehicle = Vehicle(id_veh_dep)
                    id_veh_dep_Vehicle.step_ini = simulation.step
                    num_packages = randomPackages.randint(min_packages, max_packages)
                    id_veh_dep_Vehicle.n_packages = num_packages
                    id_veh_dep_Vehicle.vType = traci.vehicle.getTypeID(id_veh_dep_Vehicle.id)
                    id_vehs_departed_Vehicle.append(id_veh_dep_Vehicle)
            simulation.add_vehicles_in_simulation(id_vehs_departed_Vehicle) # Add vehicles to the simulation list
            simulation.add_all_veh(id_vehs_departed_Vehicle)
            # Per window:
            window.add_vehicles_in_w(simulation.vehicles_in_simulation)
            window.veh_total_number_w = len(window.vehicles_in_w)

        # Taking into account the vehicles that reach their destination:
        id_vehicles_arrived = traci.simulation.getArrivedIDList()
        for veh in id_vehicles_arrived:
            for veh_sim in simulation.vehicles_in_simulation:
                if veh == veh_sim.id: # If the vehicle has arrived then remove it from the simulation
                    simulation.update_step_fin_veh(simulation.step, veh_sim)
                    simulation.remove_vehicles_in_simulation(veh_sim)
                    simulation.add_veh_total_number(1)  # Update Vehicle Total Number in all simulation
                    for veh_w in window.vehicles_in_w:
                        if veh == veh_w.id:
                            window.remove_vehicles_in_w(veh_w)
                            window.sub_veh_total_number_w(1)
                            break
                    break

        ## FOR EACH VEHICLE calculate its emisions :
        for veh in simulation.vehicles_in_simulation:
            # emissions and counting vehicles
            vehNOxEmission = traci.vehicle.getNOxEmission(veh.id)  # Return the NOx value per vehicle in each ste
            # simulation
            simulation.add_NOx_Total(vehNOxEmission)
            veh.add_NOx(vehNOxEmission)
            # Per Window
            window.add_NOx_Total_w(vehNOxEmission)
            # Control Area:
            pos = traci.vehicle.getPosition(vehID=veh.id)  # (x,y)
            if (pos[1] <= min_y and pos[1] >= max_y) and (
                        pos[0] >= min_x and pos[0] <= max_x):  # x=> 0, y=>1. If the vehicle is in the control area
                # All simulation:
                simulation.add_NOx_control_zone(vehNOxEmission)
                # Per window:
                window.add_NOx_control_zone_w(vehNOxEmission)
                # Control area:
                veh.enter_cz = True
                window.add_vehicles_in_control_zone_w(veh.id)

        ## IMPORTANT PART - FOR EACH VEHICLE analyse whether it can enter or not :
        if strategy != "noControl":
            if simulation.k >=1 : #all cars enter
                if lastkSmaller1:
                    all_cars_enter(simulation)
                lastkSmaller1=False
            elif simulation.k < 0: # no cars enter
                no_cars_enter(simulation)
                lastkSmaller1 = True
            else : #some cars enter
                some_cars_enter(simulation)
                lastkSmaller1 = True
            
        # Window
        if ((simulation.step % window_size) == 0):
            # Discount NOx of the last window:
            for w in range(len(simulation.windows)):
                if simulation.windows[w].step == simulation.step - window_size:
                    lambda_l = randomLambda.uniform(0.8, 1.2)
                    #alpha = max(0.5, min(1, lambda_l * simulation.alphas[len(simulation.alphas) - 1]))
                    #simulation.add_alpha(alpha)
                    window.lambda_l = lambda_l
                    #window.alpha = alpha
                    x_cz = lambda_l * subs_NOx
                    #for heating up if emissens are lower than e_ini, use e_ini
                    if start_control and window.NOx_control_zone_w < e_ini:
                        p_t = max(0, simulation.windows[w].p_t + e_ini - x_cz)
                    else :
                        p_t = max(0, simulation.windows[w].p_t + window.NOx_control_zone_w - x_cz)
                        start_control= False

                    y_total = x_cz * size_ratio
                    if start_total and window.NOx_total_w < (e_ini* size_ratio):
                        p_t_total = max(0, simulation.windows[w].p_t_total + (e_ini* size_ratio) - y_total)
                    else :
                        p_t_total = max(0, simulation.windows[w].p_t_total + window.NOx_total_w - y_total)
                        start_total= False

                    simulation.p_t = p_t
                    window.p_t = p_t
                    window.p_t_total = p_t_total

            # Add variables for the last 50 steps
            simulation.add_window(window)
            print("Window: ", window)

            # Reboot all

            window = Window(simulation.step, window.vehicles_in_w.copy(), window.vehicles_in_control_zone_w.copy(), 0, 0, window.veh_total_number_w)
            window.vehicles_in_control_zone_w = set()

            # CONTROL ZONE
            # calculate k
            calculate_k(simulation, window)

    minutes = round(simulation.step / 60, 0)
    """
    for v in simulation.all_veh:
        simulation.total_kilometers += v.total_km
    """

    ## RESULTS FILE 2
    cont_file = 0
    file = "results_file_" + strategy
    fileName = r"./results/" + file + str(cont_file) + ".csv"
    print(fileName)
    fileObject = Path(fileName)
    while fileObject.is_file():
        cont_file += 1
        fileName = r"./results/" + file + str(cont_file) + ".csv"
        print(fileName)
        fileObject = Path(fileName)
    f = open(fileName, "w")

    # Results:

    f.write(strategy +"\n")
    f.write("PARAMETERS,"+"\n")
    f.write("window_size, threshold_L, threshold_H, p_t_ini, min_packages, max_packages,"+"\n")
    f.write(str(window_size) +","+ str(threshold_L) +","+ str(threshold_H)  +","+ str(p_t_ini)+","+ str(min_packages) +","+ str(max_packages)+","+"\n")
    f.write("WINDOWS,"+"\n")
    f.write("step, NOx_total_w, NOx_total_acum, lambda, p_t_total, e_t_total, p_t_control_zone, e_t_control_zone, k_control_zone, num_veh_total, num_vehicles_control_zone,  "+"\n")

    acum = 0
    p_t_total_all_steps = 0
    e_t_total_all_steps = 0
    p_t_control_zone_all_steps = 0
    e_t_control_zone_all_steps = 0
    avg_k_all_steps = 0
    cont= 0
    for w in simulation.windows:
        p_t_total_all_steps += w.p_t_total
        e_t_total_all_steps += w.NOx_total_w
        p_t_control_zone_all_steps += w.p_t
        e_t_control_zone_all_steps += w.NOx_control_zone_w
        avg_k_all_steps += w.k
        cont +=1

        acum += w.NOx_total_w
        f.write(str(w.step) +","+ str(w.NOx_total_w) +","+ str(acum) +","+str(w.lambda_l)+","+str(w.p_t_total)+","+str(w.NOx_total_w)+","+str(w.p_t) +","+ str(w.NOx_control_zone_w) +","+ str(w.k)+","+ str(w.veh_total_number_w)+","+str(len(w.vehicles_in_control_zone_w))+","+"\n")
    avg_k_all_steps = avg_k_all_steps/cont

    f.write("VEHICLES,"+"\n")
    f.write("id, vType, NOx_total_veh, n_packages, step_ini, step_fin, total_time(sec),average_package,enter_cz,"+"\n")

    p_all= 0
    cont = 0
    avg_contrib = 0
    total_packages = 0
    def sortFunc(v):
        return v.step_ini
    simulation.all_veh = sorted(simulation.all_veh, key=sortFunc)

    enter_cz_all_steps = 0
    avg_total_time_all_steps = 0

    for v in simulation.all_veh:
        total_time = v.step_fin - v.step_ini
        avg_total_time_all_steps += total_time
        average_package = total_time / v.n_packages
        p_all += average_package
        cont +=1
        avg_contrib += total_time * v.n_packages
        total_packages += v.n_packages
        if v.enter_cz==False: enter_cz_all_steps +=1
        f.write(v.id  +","+ v.vType +","+ str(v.NOx)  +","+  str(v.n_packages)  +","+ str(v.step_ini) +","+  str(v.step_fin) +","+ str(total_time)+","+str(average_package) +","+ str(v.enter_cz)+","+"\n")

    avg_total_time_all_steps = avg_total_time_all_steps/cont
    average_package_all =  avg_contrib / total_packages
    f.write("ALL SIMULATION," + "\n")
    f.write("total_steps(sec), minutes, avg_package_all_sim, p_t_total_all_steps, e_t_total_all_steps, veh_enter_cz_all_steps"+ "\n")
    f.write(str(simulation.step) + "," + str(minutes)+ "," + str(average_package_all) +"," + str(p_t_total_all_steps)
            + "," + str(e_t_total_all_steps) + "," + str(p_t_control_zone_all_steps) + "," + str(e_t_control_zone_all_steps)
            + "," + str(avg_k_all_steps) +"," + str(enter_cz_all_steps) +"," + str(avg_total_time_all_steps) +"\n")

    f.close()


    # TraCI
    traci.close()
    sys.stdout.flush()
Esempio n. 4
0
def run():
    random.seed(1)
    randomLambda = random.Random()
    randomPackages = random.Random()
    print("RUN")
    simulation = Simulation(step=0,
                            threshold_L=threshold_L,
                            threshold_H=threshold_H,
                            k=1,
                            control_area_edges=control_area_edges_cnf)
    window = Window(simulation.step, set(), set(), 0, 0, 0, 0, 0, 1, 0.5, 0.8)

    while traci.simulation.getMinExpectedNumber(
    ) > 0:  # While there are cars (and waiting cars)
        # LAST STEP
        # Vehicles to control area
        vehs_load = traci.simulation.getLoadedIDList()
        vehs_load_Vehicle = []
        for veh in vehs_load:
            if veh != "simulation.findRoute":
                vehicl = Vehicle(veh)
                vehs_load_Vehicle.append(vehicl)

        simulation.vehs_load = vehs_load_Vehicle
        update_vehicles_to_control_area(simulation)

        if simulation.step == 0:
            simulation.NOx_control_zone_restriction_mode = p_t_ini
            simulation.p_t = simulation.NOx_control_zone_restriction_mode
            window.NOx_total_w = p_t_ini
            window.NOx_control_zone_w = p_t_ini
            window.p_t = p_t_ini
            window.p_t_total = p_t_ini
            window.lambda_l = 0.8
            window.alpha = alpha_ini
            simulation.add_alpha(alpha_ini)
            #print("STEP 0", simulation.alphas)
            #print(simulation.alphas[len(simulation.alphas) - 1])

            # Add variables for the last 50 steps
            simulation.add_window(window)
            print("Window: ", window)

            # Reboot all
            window = Window(simulation.step, window.vehicles_in_w.copy(),
                            set(), 0, 0, window.veh_total_number_w)

            # NEW STEP
        traci.simulationStep()  # Advance one time step: one second
        simulation.update_Step()
        window.update_Step()

        # MANAGE VEHICLES - All simulation
        id_vehs_departed = list(
            traci.simulation.getDepartedIDList())  # Vehicles in simulation

        if (id_vehs_departed):  # if the list is not empty
            # All simulation:
            id_vehs_departed_Vehicle = []
            for id_veh_dep in id_vehs_departed:
                if id_veh_dep != "simulation.findRoute":
                    id_veh_dep_Vehicle = Vehicle(id_veh_dep)
                    id_veh_dep_Vehicle.step_ini = simulation.step
                    num_packages = randomPackages.randint(
                        min_packages, max_packages)
                    id_veh_dep_Vehicle.n_packages = num_packages
                    id_veh_dep_Vehicle.vType = traci.vehicle.getTypeID(
                        id_veh_dep_Vehicle.id)
                    id_vehs_departed_Vehicle.append(id_veh_dep_Vehicle)
            simulation.add_vehicles_in_simulation(
                id_vehs_departed_Vehicle
            )  # Add vehicles to the simulation list
            simulation.add_all_veh(id_vehs_departed_Vehicle)
            # Per window:
            window.add_vehicles_in_w(simulation.vehicles_in_simulation)
            window.veh_total_number_w = len(window.vehicles_in_w)

        # Taking into account the vehicles that reach their destination:
        id_vehicles_arrived = traci.simulation.getArrivedIDList()
        for veh in id_vehicles_arrived:
            for veh_sim in simulation.vehicles_in_simulation:
                if veh == veh_sim.id:  # If the vehicle has arrived then remove it from the simulation
                    simulation.update_step_fin_veh(simulation.step, veh_sim)
                    simulation.remove_vehicles_in_simulation(veh_sim)
                    simulation.add_veh_total_number(
                        1)  # Update Vehicle Total Number in all simulation
                    for veh_w in window.vehicles_in_w:
                        if veh == veh_w.id:
                            window.remove_vehicles_in_w(veh_w)
                            window.sub_veh_total_number_w(1)
                            break
                    break

        ## IMPORTANT PART - FOR EACH VEHICLE:
        for veh in simulation.vehicles_in_simulation:
            # Emissions:
            # All simulation
            vehNOxEmission = traci.vehicle.getNOxEmission(
                veh.id)  # Return the NOx value per vehicle in each step
            simulation.add_NOx_Total(vehNOxEmission)
            veh.add_NOx(vehNOxEmission)
            #print(veh.id, veh.NOx)
            # Per Window
            window.add_NOx_Total_w(vehNOxEmission)

            # Control Area:
            pos = traci.vehicle.getPosition(vehID=veh.id)  # (x,y)

            if (pos[1] <= min_y and pos[1] >= max_y) and (
                    pos[0] >= min_x and pos[0] <= max_x
            ):  # x=> 0, y=>1. If the vehicle is in the control area
                # All simulation:
                simulation.add_NOx_control_zone(vehNOxEmission)
                # Per window:
                window.add_NOx_control_zone_w(vehNOxEmission)
                # Control area:
                simulation.add_NOx_control_zone_restriction_mode(
                    vehNOxEmission)

            # Route lenght per vehicle
            rouIndex = traci.vehicle.getRouteIndex(veh.id)
            edges = traci.vehicle.getRoute(veh.id)

            if veh not in window.vehicles_in_control_zone_w and edges[
                    rouIndex] + "_0" in control_area_edges_cnf:
                window.add_vehicles_in_control_zone_w(veh.id)
            """
            if rouIndex == (len(edges) - 1):  # Only if is the last edge
                stage = traci.simulation.findRoute(edges[0], edges[rouIndex])
                rouLength = stage.length  # Route Length
                veh.total_km = rouLength
            """

            # Control area - Threshold:
            class_veh_changer(simulation, veh)

            # REROUTE VEHICLES:
            if simulation.restrictionMode:
                inList = False
                for edg in edges:
                    edgStrng = edg + "_0"
                    if edgStrng in simulation.control_area_edges:
                        inList = True
                        break
                if inList:
                    traci.vehicle.rerouteTraveltime(veh.id, True)

        # Window
        if ((simulation.step % window_size) == 0):
            # Discount NOx of the last window:
            for w in range(len(simulation.windows)):
                if simulation.windows[w].step == simulation.step - window_size:
                    lambda_l = randomLambda.uniform(0.8, 1.2)

                    alpha = max(
                        0.5,
                        min(
                            1, lambda_l *
                            simulation.alphas[len(simulation.alphas) - 1]))
                    simulation.add_alpha(alpha)

                    window.lambda_l = lambda_l
                    window.alpha = alpha
                    """
                    p_t = alpha * simulation.windows[w].p_t + window.NOx_control_zone_w
                    p_t_total = alpha * simulation.windows[w].p_t_total + window.NOx_total_w
                    """

                    x_cz = lambda_l * subs_NOx

                    p_t = max(
                        0, simulation.windows[w].p_t +
                        window.NOx_control_zone_w - x_cz)
                    print("p_t", p_t, simulation.windows[w].p_t,
                          window.NOx_control_zone_w, x_cz)

                    y_total = x_cz * size_ratio
                    p_t_total = max(
                        0, simulation.windows[w].p_t_total +
                        window.NOx_total_w - y_total)
                    print("p_t_total", p_t_total,
                          simulation.windows[w].p_t_total, window.NOx_total_w,
                          y_total)

                    simulation.NOx_control_zone_restriction_mode = p_t
                    simulation.p_t = p_t

                    window.p_t = p_t
                    window.p_t_total = p_t_total

                    if simulation.p_t < 0:
                        simulation.NOx_control_zone_restriction_mode = 0
                        simulation.p_t = 0
                        window.p_t = 0

            # Add variables for the last 50 steps
            simulation.add_window(window)
            print("Window: ", window)

            # Reboot all

            window = Window(simulation.step, window.vehicles_in_w.copy(),
                            window.vehicles_in_control_zone_w.copy(), 0, 0,
                            window.veh_total_number_w)
            window.vehicles_in_control_zone_w = set()

            # CONTROL ZONE
            decision_maker(simulation, window)

        #print(simulation.step, "NOx_control_zone: ", simulation.NOx_control_zone, ". NOx_control_zone_restriction_mode: ", simulation.NOx_control_zone_restriction_mode, ". NOx_total: ", simulation.NOx_total)

    minutes = round(simulation.step / 60, 0)
    """
    for v in simulation.all_veh:
        simulation.total_kilometers += v.total_km
    """
    ## RESULTS FILE
    cont_file = 0
    file = "results_file_"
    fileName = r"./results/" + file + str(cont_file) + ".txt"
    print(fileName)
    fileObject = Path(fileName)
    while fileObject.is_file():
        cont_file += 1
        fileName = r"./results/" + file + str(cont_file) + ".txt"
        print(fileName)
        fileObject = Path(fileName)
    f = open(fileName, "w")

    # Results:
    print("Windows:")
    f.write("Windows:\n")
    for w in simulation.windows:
        print(w)

        vehInW = ""
        for veh in w.vehicles_in_w:
            vehInW += veh.id + ","

        cont_vehInWCZ = len(w.vehicles_in_control_zone_w)

        vehInWCZ = ""
        for veh in w.vehicles_in_control_zone_w:
            vehInWCZ += veh + ","

        f.write(
            str(w.step) + ". NOx_total_w: " + str(w.NOx_total_w) +
            ". NOx_control_zone_w: " + str(w.NOx_control_zone_w) +
            ". veh_total_number_w: " + str(w.veh_total_number_w) +
            ". Vehicles: " + vehInW + ". Nº veh in control zone: " +
            str(cont_vehInWCZ) + ". Vehicles in control zone: " + vehInWCZ +
            "\n")
    print("Vehicles:")
    f.write("Vehicles:\n")
    for v in simulation.all_veh:
        print(v)
        f.write(str(v.id) + " . Total NOx per vehicle: " + str(v.NOx) + "\n")
    print("In ", simulation.step, "seconds (", minutes, " minutes)")
    f.write("In " + str(simulation.step) + " seconds (" + str(minutes) +
            " minutes)\n")
    print("All simulation:")
    f.write("All simulation:\n")
    print(simulation)
    f.write(str(simulation.step) + ". restrictionMode: " + str(simulation.restrictionMode) + ".  NOx_total:" + str(simulation.NOx_total)+ \
               ". NOx_control_zone:" + str(simulation.NOx_control_zone) + ". veh_total_number: " + str(simulation.veh_total_number) +"\n")

    f.close()

    ## RESULTS FILE 2
    cont_file = 0
    file = "results_file_"
    fileName = r"./results2/" + file + str(cont_file) + ".csv"
    print(fileName)
    fileObject = Path(fileName)
    while fileObject.is_file():
        cont_file += 1
        fileName = r"./results2/" + file + str(cont_file) + ".csv"
        print(fileName)
        fileObject = Path(fileName)
    f = open(fileName, "w")

    # Results:

    f.write("BASELINE, " + "\n")
    f.write("PARAMETERS," + "\n")
    f.write(
        "window_size, threshold_L, threshold_H, alpha_ini, p_t_ini, min_packages, max_packages,"
        + "\n")
    f.write(
        str(window_size) + "," + str(threshold_L) + "," + str(threshold_H) +
        "," + str(alpha_ini) + "," + str(p_t_ini) + "," + str(min_packages) +
        "," + str(max_packages) + "," + "\n")
    f.write("WINDOWS," + "\n")
    f.write(
        "step, NOx_total_w, NOx_total_acum, alpha, lambda, p_t_total, e_t_total, p_t_control_zone, e_t_control_zone, k_control_zone, num_veh_total, num_vehicles_control_zone,  "
        + "\n")

    acum = 0
    for w in simulation.windows:
        acum += w.NOx_total_w
        f.write(
            str(w.step) + "," + str(w.NOx_total_w) + "," + str(acum) + "," +
            str(w.alpha) + "," + str(w.lambda_l) + "," + str(w.p_t_total) +
            "," + str(w.NOx_total_w) + "," + str(w.p_t) + "," +
            str(w.NOx_control_zone_w) + "," + str(w.k) + "," +
            str(w.veh_total_number_w) + "," +
            str(len(w.vehicles_in_control_zone_w)) + "," + "\n")

    f.write("VEHICLES," + "\n")
    f.write(
        "id, vType, NOx_total_veh, n_packages, step_ini, step_fin, total_time(sec),median_package,enter_cz,"
        + "\n")

    p_all = 0
    cont = 0
    for v in simulation.all_veh:
        total_time = v.step_fin - v.step_ini
        median_package = total_time / v.n_packages
        p_all += median_package
        cont += 1

        f.write(v.id + "," + v.vType + "," + str(v.NOx) + "," +
                str(v.n_packages) + "," + str(v.step_ini) + "," +
                str(v.step_fin) + "," + str(total_time) + "," +
                str(median_package) + "," + str(v.enter_cz) + "," + "\n")

    median_package_all = p_all / cont
    f.write("ALL SIMULATION," + "\n")
    f.write("total_steps(sec), minutes, median_package_all_sim," + "\n")
    f.write(
        str(simulation.step) + "," + str(minutes) + "," +
        str(median_package_all) + "," + "\n")

    f.close()

    # TraCI
    traci.close()
    sys.stdout.flush()