Почему этот код передает данные в неправильную строку? - PullRequest
0 голосов
/ 20 марта 2020

Я имитирую отправку сообщений, заставляя каждую машину иметь DataFrame, и когда 2 машины находятся в радиусе 30 метров, они отправляют сообщения друг другу.

Обмен сообщениями работает так, когда вы получаете сообщение, вы go в строке автомобиля, который отправил сообщение и столбец текущего времени, и заменяете 0 на 1, если сообщение получено, 0, если не получено, и 2, если получено и является критическим сообщением.

Я нахожусь на Ubuntu 18.04.4 и использую Sumo 1.3.1 с библиотекой python TraCi.

Проблема заключается в том, что когда нужно сохранять в строке X, потому что машина X отправлена насколько я видел, это сообщение сохраняется в строке X + 2. Я хочу сохранить его в правильном ряду.

Я дам вам все файлы, которые я использую в настоящее время, и весь код: https://github.com/guazco/stack_question.git, а не просто кусок, потому что с в прошлых постах были люди, которые просили весь код.

import os, sys
import optparse
import subprocess
import random
import math
import numpy as np
import pandas as pd
import multiprocessing


# we need to import python modules from the $SUMO_HOME/tools directory
try:
    sys.path.append("/home/gustavo/Downloads/sumo-1.3.1/tools")
    from sumolib import checkBinary
except ImportError:
    sys.exit("please declare environment variable 'SUMO_HOME' as the root directory of your sumo installation (it should contain folders 'bin', 'tools' and 'docs')")       
import traci

#functions to calculate the distance between 2 cars

def get_options():
    opt_parser = optparse.OptionParser()
    opt_parser.add_option("--nogui", action="store_true",
                         default=False, help="run the commandline version of sumo")
    options, args = opt_parser.parse_args()
    return options

def pos_x(x): #defining the position function to be used with map and make the program faster
    pos_x = traci.vehicle.getPosition(x)[0]
    return pos_x

def pos_y(x): #defining the position function to be used with map and make the program faster
    pos_y = traci.vehicle.getPosition(x)[1]
    return pos_y

def prob(probability):     #returns true or false based on the probability given of beeing true
    return random.random() < probability

def contamination(time,car,data_msgs): #pass on the contaminated colors to the non-contaminated cars
    threshold_lost_message = 0.2
    is_critical = random.randint(1,100) == 1 
    if random.random() > threshold_lost_message:
        if is_critical:
            data_msgs.loc[data_msgs.IDs == car,str(time) + '00ms'] = 2 
        else:
            data_msgs.loc[data_msgs.IDs == car,str(time) + '00ms'] = 1 
    # return data_msgs

def multiprocessing_func(car, j, receiver, dic_frames, car_vector, step):
    if receiver < 30 and receiver > 0.5:
        dic_frames[car_vector[j]] = contamination(step - 2,car,dic_frames[car_vector[j]]) 


# contains TraCI control loop
def run():
    step = 0
    iterator = 0
    iterator_2 = 0
    iterator_3 = 0
    dic_frames = {}
    vector_of_times = []
    simulation_duration = int(input("Insert the simulation's duration in miliseconds: "))
    for iterator in range(simulation_duration):
        vector_of_times.append(str(iterator + 1) + "00ms")
    frame_base = pd.DataFrame(columns = vector_of_times)
    for iterator_2 in range(300):
        frame_base.loc[str(iterator_2)] = 0
    for iterator_3 in range(300):
        dic_frames[str(iterator_3)] = frame_base.copy()

    while traci.simulation.getMinExpectedNumber() > 0: #while there are cars in the simulation it goes on, so to stop it you have to use the terminal itself
        traci.simulationStep()
        step += 1  
        if step > 2 and step < simulation_duration: # it gives time to various car to enter the simulation

            car_vector = list(traci.vehicle.getIDList()) # actualizes the list of cars

            for i in car_vector: #reroutes cars so they dont get out of the simulation
                if traci.vehicle.getRouteIndex(str(i)) == (len(traci.vehicle.getRoute(str(i))) - 1): #verification to see if the car is at the end of its route
                    new_destiny = random.choice(traci.edge.getIDList()) #sets a new edge to send the vehicle
                    while (new_destiny[0] == ':'): #garantees that some edges impossible to set as new destinies are not set
                        new_destiny = random.choice(traci.edge.getIDList()) 
                    traci.vehicle.changeTarget(str(i),str(new_destiny)) #changes the current destination to the new one

            pos_vector_x = np.array(list(map(pos_x,car_vector))) #gets position of all the cars in the simulation in numpy arrays to facilitate calculations, this library uses some means as paralelization to make it faster
            pos_vector_y = np.array(list(map(pos_y,car_vector))) #it also uses the map function with the same objective as the numpy library


            for car in car_vector:
                dist = np.sqrt((pos_vector_x - traci.vehicle.getPosition(car)[0])**2 + (pos_vector_y - traci.vehicle.getPosition(car)[1])**2) #creates a vector with all distances from the cars in the simulation and the car being used in the moment
                threshold_lost_message = 0.2 #chance 
                is_critical =  np.random.choice([1, 2], size=len(car_vector), p=[.99, .01])
                lost = np.random.random(size=len(car_vector)) < threshold_lost_message
                cond = (dist >= 30) | (dist <= 0.5) | lost
                cond2 = np.logical_not(cond)            
                print(car, len(car_vector), dic_frames[car].shape, dic_frames[car].loc[car_vector, str(step-2) + '00ms'].shape)
                dic_frames[car].loc[car_vector, str(step-2) + '00ms'] = dic_frames[car].loc[car_vector, str(step-2) + '00ms'].where(cond, other=is_critical)
                print(car_vector)

        if step == simulation_duration:
            for key in dic_frames:
                export_csv = dic_frames[key].to_csv(r'/home/gustavo/Desktop/Usp/teste' + str(key) + '.csv', index = None, header=True)
    traci.close()
    sys.stdout.flush()

# main entry point
if __name__ == "__main__":
    options = get_options()

    # check binary
    if options.nogui:
        sumoBinary = checkBinary('sumo')
    else:
        sumoBinary = checkBinary('sumo-gui')

    # traci starts sumo as a subprocess and then this script connects and runs
    traci.start([sumoBinary, "-c", "usp.sumocfg",
                             "--tripinfo-output", "tripinfo.xml"])
    run()
...