Ejemplo n.º 1
0
def test_gforces(beamng):
    with beamng as bng:
        scenario = Scenario('west_coast_usa', 'gforce_test')
        vehicle = Vehicle('test_car', model='etk800')

        gforces = GForces()
        vehicle.attach_sensor('gforces', gforces)

        scenario.add_vehicle(vehicle,
                             pos=(-717.121, 101, 118.675),
                             rot=(0, 0, 45))
        scenario.make(beamng)

        gx = []
        gy = []
        bng.load_scenario(scenario)
        bng.start_scenario()
        bng.step(120)

        vehicle.ai_set_aggression(2)
        vehicle.ai_set_mode('span')

        for _ in range(64):
            bng.step(30)
            vehicle.poll_sensors()
            gx.append(gforces.data['gx'])
            gy.append(gforces.data['gy'])

    assert np.var(gx) > 1 and np.var(gy) > 1
Ejemplo n.º 2
0
def setup_beamng(traffic=2):
    global sp, beamng_home, beamng_user
    setup_logging()
    beamng = BeamNGpy('localhost', 64256, home=beamng_home, user=beamng_user)
    scenario = Scenario(
        'west_coast_usa',
        'lidar_tour',
        description=
        'Tour through highway with variable traffic vehicles gathering '
        'Lidar data')
    # setup vehicle
    vehicle = Vehicle('ego_vehicle',
                      model='etk800',
                      licence='LIDAR',
                      color='Red')
    vehicle = setup_sensors(vehicle)

    # setup vehicle poses
    lane = random.choice([1, 2, 3, 4])
    ego_sp = spawn_point(sp, lane)
    ego_pos = ego_sp['pos']
    ego_rot_quat = ego_sp['rot_quat']
    lane = ego_sp['lane']
    # add vehicles to scenario
    # print("adding vehicle to scenario...")
    scenario.add_vehicle(vehicle, pos=ego_pos, rot=None, rot_quat=ego_rot_quat)
    tvs = traffic_vehicles(traffic)
    ps = generate_vehicle_positions(ego_pos, ego_rot_quat, lane, tvs)
    for i in range(len(tvs)):
        print("adding vehicle {}...".format(i))
        scenario.add_vehicle(tvs[i], pos=ps[i], rot_quat=ego_rot_quat)
    print("making scenario...")
    scenario.make(beamng)
    print("opening beamNG...")
    bng = beamng.open(launch=True)
    st = time.time()

    print("loading scenario...")
    bng.load_scenario(scenario)

    bng.set_steps_per_second(60)
    bng.set_deterministic()
    #print("Bounding box: {}".format(vehicle.get_bbox()))
    bng.hide_hud()
    print("starting scenario...")
    bng.start_scenario()
    vehicle.ai_set_mode('traffic')
    #"DecalRoad31765_8"
    vehicle.ai_drive_in_lane(False)
    vehicle.ai_set_aggression(2.0)
    bng.start_traffic(tvs)
    bng.switch_vehicle(vehicle)
    bng.pause()
    return vehicle, bng
Ejemplo n.º 3
0
import mmap
Ejemplo n.º 4
0
def main():
    global base_filename, training_dir, default_model

    f = setup_dir(training_dir)
    spawn_pt = spawn_point(default_scenario)
    random.seed(1703)
    setup_logging()

    beamng = BeamNGpy('localhost', 64256, home='C:/Users/merie/Documents/BeamNG.research.v1.7.0.1')
    scenario = Scenario(default_scenario, 'research_test')
    vehicle = Vehicle('ego_vehicle', model=default_model,
                      licence='RED', color='Red')
    vehicle = setup_sensors(vehicle)
    scenario.add_vehicle(vehicle, pos=spawn_pt['pos'], rot=None, rot_quat=spawn_pt['rot_quat'])

    # Compile the scenario and place it in BeamNG's map folder
    scenario.make(beamng)

    # Start BeamNG and enter the main loop
    bng = beamng.open(launch=True)
    images = []

    bng.hide_hud()
    bng.set_deterministic()  # Set simulator to be deterministic
    bng.set_steps_per_second(60)  # With 60hz temporal resolution

    # Load and start the scenario
    bng.load_scenario(scenario)
    bng.start_scenario()

    vehicle.ai_set_mode('span')
    vehicle.ai_drive_in_lane(True)
    vehicle.ai_set_aggression(0.1)

    # Put simulator in pause awaiting further inputs
    bng.pause()
    assert vehicle.skt

    # Send random inputs to vehice and advance the simulation 20 steps
    imagecount = 0
    wheelvel = [0.1, 0.1, 0.1]
    with open(f, 'w') as datafile:
        datafile.write('filename,timestamp,steering_input,throttle_input,brake_input,driveshaft,engine_load,fog_lights,fuel,'
                       'lowpressure,oil,oil_temperature,parkingbrake,rpm,water_temperature\n')
        #for _ in range(1024):
        for _ in range(32768):
            #throttle = 1.0 #random.uniform(0.0, 1.0)
            #steering = random.uniform(-1.0, 1.0)
            #brake = random.choice([0, 0, 0, 1])
            #vehicle.control(throttle=throttle)

            # collect images
            sensors = bng.poll_sensors(vehicle)
            image = sensors['front_cam']['colour'].convert('RGB')
            imagecount += 1
            filename = "{}{}.bmp".format(base_filename, imagecount)

            # collect ancillary data
            datafile.write('{},{},{},{},{},{},{},{},{},{},{},{},{},{}\n'.format(filename,
                                                str(round(sensors['timer']['time'], 2)),
                                                sensors['electrics']['steering_input'],
                                                sensors['electrics']['throttle_input'],
                                                sensors['electrics']['brake_input'],
                                                sensors['electrics']['driveshaft'],
                                                sensors['electrics']['engine_load'],
                                                sensors['electrics']['fog_lights'],
                                                sensors['electrics']['fuel'],
                                                sensors['electrics']['lowpressure'],
                                                sensors['electrics']['oil'],
                                                sensors['electrics']['oil_temperature'],
                                                sensors['electrics']['parkingbrake'],
                                                sensors['electrics']['rpm'],
                                                sensors['electrics']['water_temperature'],))

            # save the image
            image.save(filename)

            # step sim forward
            bng.step(20)
            print('{} seconds passed.'.format(str(round(sensors['timer']['time'], 2))))

            # check for stopping condition
            for i in range(len(wheelvel)-1):
                wheelvel[i] = wheelvel[i+1]
            wheelvel[2] = float(sensors['electrics']['wheelspeed'])
            print('wheelvel = {}'.format(sum(wheelvel) / 3.0 ))
            if sum(wheelvel) / 3.0 == 0.0:
                print("avg wheelspeed is zero; exiting...")
                bng.close()
                break
def run_scenario(traffic=2, run_number=0):
    global sp
    setup_logging()
    beamng = BeamNGpy('localhost',
                      64256,
                      home='C:/Users/merie/Documents/BeamNG.research.v1.7.0.1')
    scenario = Scenario('west_coast_usa',
                        'lidar_tour',
                        description='Tour through the west coast gathering '
                        'Lidar data')
    vehicle = Vehicle('ego_vehicle',
                      model='etk800',
                      licence='LIDAR',
                      color='Red')
    vehicle = setup_sensors(vehicle)
    lidar = setup_lidar('hood')
    vehicle.attach_sensor('lidar', lidar)
    ego_sp = spawn_point(sp)
    ego_pos = ego_sp['pos']
    ego_rot_quat = ego_sp['rot_quat']
    scenario.add_vehicle(vehicle, pos=ego_pos, rot=None, rot_quat=ego_rot_quat)
    tvs = traffic_vehicles(traffic)
    ps = generate_vehicle_positions(ego_pos, ego_rot_quat, tvs)
    for i in range(len(tvs)):
        scenario.add_vehicle(tvs[i], pos=ps[i], rot_quat=ego_rot_quat)
    scenario.make(beamng)
    bng = beamng.open(launch=True)
    try:
        bng.load_scenario(scenario)
        bng.set_steps_per_second(60)
        #bng.set_deterministic()
        #print("Bounding box: {}".format(vehicle.get_bbox()))
        bng.hide_hud()
        bng.start_scenario()
        vehicle.ai_set_mode('traffic')
        vehicle.ai_drive_in_lane(True)
        #vehicle.ai_set_speed(16, mode='limit')
        #vehicle.ai_set_target('traffic')
        vehicle.ai_set_aggression(0.9)
        bng.start_traffic(tvs)
        bng.switch_vehicle(vehicle)
        start = time.time()
        end = time.time()
        damage_prev = None
        with open(
                'H:/traffic_traces/traffic_lidar_data_{}traffic_run{}.csv'.
                format(traffic, run_number), 'w') as f:
            f.write(
                "TIMESTAMP,VEHICLE_POSITION,VEHICLE_ORIENTATION,VELOCITY,LIDAR,CRASH,EXTERNAL_VEHICLES \n"
            )
            for _ in range(1024):
                sensors = bng.poll_sensors(vehicle)
                points = sensors['lidar']['points']
                damage = sensors['damage']
                v_state = vehicle.state
                #print("vehicle_state = {}".format(v_state))
                ai_state = vehicle.ai_get_state()
                #print("ai_state = {}".format(ai_state))
                new_damage = diff_damage(damage, damage_prev)
                damage_prev = damage
                if new_damage > 0:
                    print("new damage = {}".format(new_damage))
                f.write("{},{},{},{},{},{},{}\n".format(
                    _ * 0.5, v_state['pos'], v_state['dir'], v_state['vel'],
                    points.tolist(), str(new_damage), traffic))
                #print("Time passed since last step: {}".format(time.time() - end))
                end = time.time()
                #print("Time passed since scenario begun: {}\n".format(end - start))
                print()
                if end - start >= 45:
                    bng.close()
                bng.step(30, wait=False)
    except Exception as e:
        print(e)
    finally:
        bng.close()
def main():
    setup_logging()

    beamng = BeamNGpy('localhost',
                      64256,
                      home='C:/Users/merie/Documents/BeamNG.research.v1.7.0.1')
    scenario = Scenario(
        'west_coast_usa',
        'lidar_tour',
        description='Tour through the west coast gathering Lidar data')
    vehicle = Vehicle('ego_vehicle', model='etk800', licence='LIDAR')
    vehicle = setup_sensors(vehicle)
    lidar = setup_lidar('hood')
    vehicle.attach_sensor('lidar', lidar)
    spawn_pt = spawn_point()
    ego_pos = spawn_pt['pos']
    ego_rot_quat = spawn_pt['rot_quat']
    scenario.add_vehicle(vehicle, pos=ego_pos, rot=None, rot_quat=ego_rot_quat)
    tvs = traffic_vehicles()
    scenario.make(beamng)
    bng = beamng.open(launch=True)

    #try:
    bng.load_scenario(scenario)
    bng.set_steps_per_second(60)
    bng.set_deterministic()
    bng.hide_hud()
    bng.start_scenario()
    vehicle.ai_set_mode('traffic')
    vehicle.ai_set_aggression(0.5)
    vehicle.ai_drive_in_lane(True)
    #vehicle.ai_set_speed(16, mode='limit')
    #vehicle.ai_set_target('traffic')
    bng.switch_vehicle(vehicle)
    damage_prev = None
    start = time.time()
    end = time.time()
    bng.pause()
    print("Bounding box: {}".format(vehicle.get_bbox()))
    with open('lidar_data.csv', 'w') as f:
        f.write(
            "TIMESTAMP,VEHICLE_POSITION,VEHICLE_ORIENTATION,VELOCITY,LIDAR,CRASH\n"
        )
        for _ in range(1024):

            sensors = bng.poll_sensors(vehicle)
            points = sensors['lidar']['points']
            damage = sensors['damage']
            v_state = vehicle.state
            print("vehicle_state = {}".format(v_state))
            print("vehicle_state[pos] = {}".format(v_state['pos']))
            print("vehicle_state[dir] = {}".format(v_state['dir']))
            print("Vehicle bounding box:{}".format(vehicle.get_bbox()))
            #ai_state = vehicle.ai_get_state()
            #print("ai_state = {}".format(ai_state))
            new_damage = diff_damage(damage, damage_prev)
            damage_prev = damage
            #print("new damage = {}".format(new_damage))
            print()

            f.write("{},{},{},{},{},{}\n".format(_ * 0.5, v_state['pos'],
                                                 v_state['dir'],
                                                 v_state['vel'],
                                                 points.tolist(),
                                                 str(new_damage)))
            #bng.step(30, wait=False)
            bng.step(30)
            #print("Time passed since last step: {}".format(time.time() - end))
            end = time.time()
            #print("Time passed since scenario begun: {}\n".format(end - start))

            #screenrecord()

            if end - start >= 30:
                #bng.close()
                continue
Ejemplo n.º 7
0
def testrun(speed=11, risk=0.6):
    global base_filename, training_dir, default_model, setpoint
    global spawnpoint

    f = setup_dir(training_dir)
    spawn_pt = spawn_point(default_scenario, spawnpoint)
    random.seed(1703)
    setup_logging()

    beamng = BeamNGpy('localhost',
                      64256,
                      home='H:/BeamNG.research.v1.7.0.1clean',
                      user='******')
    scenario = Scenario(default_scenario, 'research_test')
    # add barriers and cars to get the ego vehicle to avoid the barriers
    add_barriers(scenario)
    # add_barrier_cars(scenario)
    vehicle = Vehicle('ego_vehicle',
                      model=default_model,
                      licence='RED',
                      color='White')
    vehicle = setup_sensors(vehicle)
    scenario.add_vehicle(vehicle,
                         pos=spawn_pt['pos'],
                         rot=None,
                         rot_quat=spawn_pt['rot_quat'])

    # Compile the scenario and place it in BeamNG's map folder
    scenario.make(beamng)

    # Start BeamNG and enter the main loop
    bng = beamng.open(launch=True)

    #bng.hide_hud()
    bng.set_nondeterministic()  # Set simulator to be deterministic
    bng.set_steps_per_second(36)  #

    # Load and start the scenario
    bng.load_scenario(scenario)
    bng.start_scenario()
    bng.switch_vehicle(vehicle)

    vehicle.ai_set_mode('traffic')
    vehicle.ai_drive_in_lane(False)
    vehicle.ai_set_speed(speed, mode='set')
    vehicle.ai_set_aggression(risk)

    # Put simulator in pause awaiting further inputs
    bng.pause()
    assert vehicle.skt
    # bng.resume()
    start_time = time.time()
    # Send random inputs to vehicle and advance the simulation 20 steps
    imagecount = 0
    with open(f, 'w') as datafile:
        datafile.write(
            'filename,timestamp,steering_input,throttle_input,brake_input,driveshaft,engine_load,fog_lights,fuel,'
            'lowpressure,oil,oil_temperature,parkingbrake,rpm,water_temperature,wheelspeed\n'
        )
        reached_start = False
        vels = []
        vel_dict = {}
        while imagecount < 10000:
            # collect images
            sensors = bng.poll_sensors(vehicle)
            image = sensors['front_cam']['colour'].convert('RGB')
            full_filename = "{}{}{}.jpg".format(training_dir, base_filename,
                                                imagecount)
            qualified_filename = "{}{}.jpg".format(base_filename, imagecount)

            # collect ancillary data
            datafile.write(
                '{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}\n'.format(
                    qualified_filename, str(
                        round(sensors['timer']['time'],
                              2)), sensors['electrics']['steering_input'],
                    sensors['electrics']['throttle_input'],
                    sensors['electrics']['brake_input'],
                    sensors['electrics']['driveshaft'],
                    sensors['electrics']['engine_load'],
                    sensors['electrics']['fog_lights'],
                    sensors['electrics']['fuel'],
                    sensors['electrics']['lowpressure'],
                    sensors['electrics']['oil'],
                    sensors['electrics']['oil_temperature'],
                    sensors['electrics']['parkingbrake'],
                    sensors['electrics']['rpm'],
                    sensors['electrics']['water_temperature'],
                    sensors['electrics']['wheelspeed']))
            if sensors['timer']['time'] > 10:
                kph = sensors['electrics']['wheelspeed'] * 3.6
                vels.append(kph)
                vel_dict[sensors['timer']['time']] = kph

            if distance(spawn_pt['pos'], vehicle.state['pos']
                        ) < 5 and sensors['timer']['time'] > 10:
                reached_start = True
                break

            if sensors['damage']['damage'] > 0:
                print("CRASHED; QUITTING")
                break

            # save the image
            image.save(full_filename)
            imagecount += 1

            # plt.title("90 degrees FOV")
            # plt.imshow(image)
            # plt.pause(0.01)
            # plt.title("120 degrees FOV")
            # plt.imshow(sensors['back_cam']['colour'].convert('RGB'))
            # plt.pause(0.01)
            # step sim forward
            bng.step(1, wait=True)
        wheelspeed_avg = round((sum(vels) / float(len(vels))), 3)
        wheelspeed_var = round(np.var(vels), 3)
        return_str = ''
        if sensors['damage']['damage'] > 0:
            # print("QUIT DUE TO CRASH VALUE {}".format(sensors['damage']['damage']))
            return_str = "QUIT DUE TO CRASH VALUE {}".format(
                sensors['damage']['damage'])
            print(return_str)
        maxtime = from_val_get_key(vel_dict, max(vels))
        mintime = from_val_get_key(vel_dict, min(vels))
        info = "IMAGE COUNT:{}\nSIM TIME:{} WALLCLOCK TIME:{}\nWHEELSPEED AVG:{} VAR:{} \nMAX:{} @ timestep {} MIN:{} @ timestep {} ".format(
            imagecount, str(round(sensors['timer']['time'], 2)),
            time.time() - start_time, wheelspeed_avg, wheelspeed_var,
            round(max(vels), 3), round(maxtime, 3), round(min(vels), 3),
            round(mintime, 3))
        print("SPEED:{} RISK:{}".format(speed, risk))
        print(info)
        return_str = "{}\n{}".format(return_str, info)
        bng.close()
        return return_str
def main():
    global sp
    setup_logging()

    beamng = BeamNGpy('localhost', 64256, home='H:/BeamNG.research.v1.7.0.1clean')
    scenario = Scenario('west_coast_usa', 'lidar_tour',
                        description='Tour through the west coast gathering '
                                    'Lidar data')

    vehicle = Vehicle('ego_vehicle', model='etk800', licence='LIDAR', color='Red')
    lidar = Lidar()
    lidar.__init__(offset=(0, 0, 1.7), direction=(-0.707, -0.707, 0), vres=32,
                   vangle=0.01, rps=2200000, hz=20, angle=360, max_dist=200,
                   visualized=True)
    vehicle.attach_sensor('lidar', lidar)
    ego_sp = spawn_point(sp)
    ego_pos = ego_sp['pos']
    ego_rot_quat = ego_sp['rot_quat']
    scenario.add_vehicle(vehicle, pos=ego_pos, rot=None, rot_quat=ego_rot_quat)
    tvs = traffic_vehicles()
    #ps = [(-722.121, 103, 118.675), (-714.121, 101, 118.675), (-715.121, 105, 118.675), (-721.121, 100, 118.675)]
    ps = [(ego_pos[0]-10, ego_pos[1]+2, ego_pos[2]),
          (ego_pos[0]-10, ego_pos[1]-2, ego_pos[2]),
          (ego_pos[0]-14, ego_pos[1]+5, ego_pos[2]),
          (ego_pos[0]+5, ego_pos[1]-1, ego_pos[2]),
          (ego_pos[0]+8, ego_pos[1]-4, ego_pos[2]),
          (ego_pos[0]+10, ego_pos[1]+9, ego_pos[2]),
          (ego_pos[0]+1, ego_pos[1]+11, ego_pos[2])]
    ps1 = [(ego_pos[0] - 10, ego_pos[1] + 3, ego_pos[2]),
          (ego_pos[0] - 10, ego_pos[1] - 1, ego_pos[2]),
          (ego_pos[0] - 14, ego_pos[1] + 5, ego_pos[2]),
          (ego_pos[0] + 5, ego_pos[1] - 1, ego_pos[2]),
          (ego_pos[0] + 8, ego_pos[1] - 4, ego_pos[2]),
          (ego_pos[0] + 10, ego_pos[1] + 9, ego_pos[2]),
          (ego_pos[0] + 1, ego_pos[1] + 11, ego_pos[2])]
    ps_oldorig = [(ego_pos[0]-7, ego_pos[1]+3, ego_pos[2]),
          (ego_pos[0]+5, ego_pos[1]-1, ego_pos[2]),
          (ego_pos[0]+4, ego_pos[1]+5, ego_pos[2]),
          (ego_pos[0]+5, ego_pos[1]-1, ego_pos[2]),
          (ego_pos[0]+8, ego_pos[1]-4, ego_pos[2]),
          (ego_pos[0]+10, ego_pos[1]+9, ego_pos[2]),
          (ego_pos[0]+1, ego_pos[1]+11, ego_pos[2])]
    for i in range(len(tvs)):
        scenario.add_vehicle(tvs[i], pos=ps[i], rot_quat=ego_rot_quat)
    scenario.make(beamng)
    bng = beamng.open(launch=True)

    try:
        bng.load_scenario(scenario)
        bng.set_steps_per_second(60)
        bng.set_deterministic()
        bng.hide_hud()
        bng.start_scenario()
        vehicle.ai_set_mode('traffic')
        vehicle.ai_drive_in_lane(True)
        #vehicle.ai_set_speed(16, mode='limit')
        #vehicle.ai_set_target('traffic')
        vehicle.ai_set_aggression(0.5) #0.7)
        bng.start_traffic(tvs)
        bng.switch_vehicle(vehicle)

        start = time.time()
        end = time.time()
        damage_prev = bng.poll_sensors(vehicle)
        with open('lidar_data.csv', 'w') as f:
            for _ in range(1024):
                sensors = bng.poll_sensors(vehicle)
                points = sensors['lidar']['points']
                #print(points.tolist())
                #print()
                #f.write("{}\n".format(points.tolist()))

                print("Time passed since last step: {}".format(time.time() - end))
                end = time.time()
                print("Time passed since scenario begun: {}\n".format(end - start))
                if end - start >= 30:
                    bng.close()

                bng.step(30, wait=False)

    except Exception as e:
        print(e)
    finally:
        bng.close()
Ejemplo n.º 9
0
def run_sim(nodes, ai_aggression, street_1: DecalRoad, street_2: DecalRoad):
    waypoint_goal = BeamNGWaypoint('waypoint_goal',
                                   get_node_coords(street_1.nodes[-1]))

    maps.beamng_map.generated().write_items(street_1.to_json() + '\n' +
                                            waypoint_goal.to_json() + '\n' +
                                            street_2.to_json())

    beamng = BeamNGpy('localhost', 64256)
    scenario = Scenario('tig', 'tigscenario')

    vehicle = Vehicle('ego_vehicle',
                      model='etk800',
                      licence='TIG',
                      color='Red')

    sim_data_collector = TrainingDataCollectorAndWriter(
        vehicle, beamng, street_1)

    scenario.add_vehicle(vehicle,
                         pos=get_node_coords(street_1.nodes[0]),
                         rot=get_rotation(street_1))

    scenario.make(beamng)

    beamng.open()
    beamng.set_deterministic()
    beamng.load_scenario(scenario)
    beamng.pause()
    beamng.start_scenario()

    vehicle.ai_set_aggression(ai_aggression)
    vehicle.ai_drive_in_lane(True)
    # vehicle.ai_set_speed(25.0 / 4)
    vehicle.ai_set_waypoint(waypoint_goal.name)
    # vehicle.ai_set_mode("manual")

    # sleep(5)

    steps = 5

    print(nodes)
    print(beamng.get_road_edges("street_1"))

    def start():
        for idx in range(1000):
            if (idx * 0.05 * steps) > 3.:
                sim_data_collector.collect_and_write_current_data()
                dist = distance(sim_data_collector.last_state.pos,
                                waypoint_goal.position)
                if dist < 15.0:
                    beamng.resume()
                    break

            # one step is 0.05 seconds (5/100)
            beamng.step(steps)

    try:
        start()
    finally:

        beamng.close()