Esempio n. 1
0
def convert_test(dbc, dbe):
    """Starts a test in DriveBuild to convert xml files to prefab, json and lua files. Moves them automatically to
    the scenario folder in the BeamNG trunk folder.
    :return: Void.
    """
    service = AIExchangeService("localhost", 8383)
    service.run_tests("test", "test", Path(dbe), Path(dbc))
    print(
        colored(
            "Converting XML files to BNG files. Moving to scenarios folder...",
            "blue"))

    # Close BeamNG after converting. If you don't close it, BeamNG will load.
    call("C:\\Windows\\System32\\taskkill.exe /f /im BeamNG.research.x64.exe",
         shell=True)

    # Change it to YOUR DriveBuild user path.
    destination_path = "C:\\BeamNG.research_userpath\\drivebuild_*"
    matches = glob(destination_path)
    if len(matches) > 0:
        latest_folder = max(matches, key=os.path.getmtime)
        latest_folder = latest_folder + "\\levels\\drivebuild\\scenarios\\*"
        matches = glob(latest_folder)
        if len(matches) != 0:
            latest_file = max(matches, key=os.path.getmtime)
            elements = latest_file.split("\\")
            filename = elements[-1].split(".")[0]
            destination_path = latest_folder[:-1] + filename + "*"
            matches = glob(destination_path)
            for match in matches:
                # Change it to YOUR DriveBuild scenario folder in the BNG trunk folder.
                shutil.move(
                    match,
                    "D:\\Program Files (x86)\\BeamNG\\levels\\drivebuild\\scenarios"
                )
Esempio n. 2
0
def _start_moose_test():
    from drivebuildclient.aiExchangeMessages_pb2 import VehicleID
    from drivebuildclient.AIExchangeService import AIExchangeService
    from dummy_ai import DummyAI
    from os.path import dirname, join
    from pathlib import Path
    service = AIExchangeService("localhost", 8383)
    upload_result = service.run_tests("test", "test", Path(join(dirname(__file__), "scenario")))
    if upload_result and upload_result.submissions:
        for test_name, sid in upload_result.submissions.items():
            vid = VehicleID()
            vid.vid = "ego"
            DummyAI(service).start(sid, vid)
Esempio n. 3
0
def main() -> None:
    from drivebuildclient.AIExchangeService import AIExchangeService
    from drivebuildclient.aiExchangeMessages_pb2 import VehicleID
    from common.dummy_ai import DummyAI
    from pathlib import Path
    from os.path import dirname, join
    service = AIExchangeService("localhost", 5000)
    upload_result = service.run_tests(
        "test", "test", Path(join(dirname(__file__), "providedFiles")))
    if upload_result and upload_result.submissions:
        for test_name, sid in upload_result.submissions.items():
            vid = VehicleID()
            vid.vid = "ego"
            DummyAI(service).start(sid, vid)
Esempio n. 4
0
    def start(self, sid: SimulationID, vid: VehicleID) -> None:
        from drivebuildclient.AIExchangeService import AIExchangeService
        from drivebuildclient.aiExchangeMessages_pb2 import SimStateResponse, DataRequest, Control
        service = AIExchangeService("localhost", 8383)
        while True:
            print(sid.sid + ": Test status: " + service.get_status(sid))
            # Wait for the simulation to request this AI
            sim_state = service.wait_for_simulator_request(sid, vid)
            if sim_state is SimStateResponse.SimState.RUNNING:  # Check whether simulation is still running
                # Request data this AI needs
                request = DataRequest()
                request.request_ids.extend([])  # Add all IDs of data to be requested
                data = service.request_data(sid, vid, request)  # Request the actual data

                # Calculate commands controlling the car
                control = Control()
                # Define a control command like
                # control.avCommand.accelerate = <Some value between 0.0 and 1.0>
                # control.avCommand.steer = <Some value between -1.0 (left) and 1.0 (right)
                # control.avCommand.brake = <Some value between 0.0 and 1.0>
                service.control(sid, vid, control)
            else:
                print(sid.sid + ": The simulation is not running anymore (Final state: "
                      + SimStateResponse.SimState.Name(sim_state) + ").")
                print(sid.sid + ": Final test result: " + service.get_result(sid))
                # Clean up everything you have to
                break
 def onTestFinished(self, sid, vid):
     """This method is called after a test was finished in DriveBuild.
     Also updates fitness value of an individual.
     :param sid: Simulation ID.
     :param vid: Vehicle ID (only one participant).
     :return: Void.
     """
     # Change service if your configuration differs.
     service = AIExchangeService("localhost", 8383)
     trace_data = service.get_trace(sid, vid)
     distances = []
     for i in range(0, len(trace_data)):
         distances.append(
             trace_data[i]
             [3].data["egoLaneDist"].road_center_distance.distance)
     ticks = trace_data[-1][2]
     self._calculate_fitness_value(distances, ticks)
Esempio n. 6
0
def _main() -> None:
    from pathlib import Path
    _configure_asfault()
    test = _generate_asfault_test()
    lanes = _get_lanes(test)

    dbe_content = _generate_dbe(lanes)
    temp_dbe_file = NamedTemporaryFile(mode="w",
                                       delete=False,
                                       suffix=".dbe.xml")
    temp_dbe_file.write(dbe_content)
    temp_dbe_file.close()

    # FIXME Choose lane based on some ranking?
    dbc_content = _generate_dbc(lanes[0], basename(temp_dbe_file.name))
    temp_dbc_file = NamedTemporaryFile(mode="w",
                                       delete=False,
                                       suffix=".dbc.xml")
    temp_dbc_file.write(dbc_content)
    temp_dbc_file.close()

    service = AIExchangeService("defender.fim.uni-passau.de", 8383)
    submission_result = service.run_tests("test", "test",
                                          Path(temp_dbe_file.name),
                                          Path(temp_dbc_file.name))
    if submission_result and submission_result.submissions:
        for test_name, sid in submission_result.submissions.items():
            vid = VehicleID()
            vid.vid = "ego"
            while True:
                sim_state = service.wait_for_simulator_request(sid, vid)
                if sim_state != SimStateResponse.SimState.RUNNING:
                    break
            print("Result of \"" + test_name + "\": " +
                  service.get_result(sid))
            break  # NOTE Assume only one test was uploaded
    else:
        _LOGGER.warning("DriveBuild denied running the given test.")

    remove(temp_dbe_file.name)
    remove(temp_dbc_file.name)
def main():
    print("parameters: ")
    for i in range(1, len(sys.argv)):
        print(sys.argv[i])
    data_request_path = sys.argv[1]
    ai_path = sys.argv[2]
    working_directory = sys.argv[3]
    """
    data_request_path = "C:\\sbse4tac-ws-2019-self-driving-car-e2edriving\\ai\\data_requests.py"
    ai_path = "C:\\sbse4tac-ws-2019-self-driving-car-e2edriving\\run_db.py"
    working_directory = "C:\\sbse4tac-ws-2019-self-driving-car-e2edriving"
    """

    service = AIExchangeService("localhost", 8383)

    vid = VehicleID()
    vid.vid = "ego"

    tg = TestGenerator()
    tg.set_difficulty("easy")
    while True:
        for paths in tg.getTest():
            criteria = paths[1]
            environment = paths[0]

            # edit the xml
            spec = importlib.util.spec_from_file_location(
                "AI", data_request_path)
            foo = importlib.util.module_from_spec(spec)
            # Actually run the import
            spec.loader.exec_module(foo)

            # get ai element
            double_backslash_dbc_path = str(criteria).replace(
                "\\", "\\" + "\\")
            tree = parse(double_backslash_dbc_path)
            root = tree.getroot()
            for i in range(0, len(root.getchildren())):
                if root.getchildren(
                )[i].tag == "{http://drivebuild.com}participants":
                    participant_block = root.getchildren()[i].getchildren()[0]
                    for j in range(0, len(participant_block)):
                        part_child = participant_block.getchildren()[j]
                        if part_child.tag == "{http://drivebuild.com}ai":
                            pass
                            part_child.clear()
                            foo.add_data_requests(part_child, "ego")
                            pass
            # write the changed xml
            # TODO pretty print
            f = open(double_backslash_dbc_path, "w")
            f.write(tostring(root, pretty_print=True).decode("utf-8"))
            f.close()

            # ai: _Element = ai_tag.makeelement(_tag="speed")

            submission_result = service.run_tests("test", "test", environment,
                                                  criteria)
            # Interact with a simulation
            if submission_result and submission_result.submissions:
                for test_name, sid in submission_result.submissions.items():
                    ai_process = subprocess.Popen([env_path, ai_path, sid.sid],
                                                  cwd=working_directory)

                    sim_state = service.wait_for_simulator_request(sid, vid)
                    while sim_state is SimStateResponse.SimState.RUNNING:
                        sleep(5)
                        sim_state = service.wait_for_simulator_request(
                            sid, vid)

                    # TODO Use a trap or try except to ensure we kill the process
                    kill_process(ai_process)
                    sleep(5)
                    tg.onTestFinished(sid, vid)
Esempio n. 8
0
                control.avCommand.steer = steer
                control.avCommand.brake = brake
            service.control(sid, vid_obj, control)  # control()
        else:
            print(sid.sid + ": The simulation is not running anymore (State: "
                  + SimStateResponse.SimState.Name(sim_state) + ").")
            print(sid.sid + ": Final result: " + service.get_result(sid))
            break


if __name__ == "__main__":
    from drivebuildclient.AIExchangeService import AIExchangeService
    from drivebuildclient.aiExchangeMessages_pb2 import SimStateResponse, Control, SimulationID, VehicleID, DataRequest
    from keyboard import is_pressed

    service = AIExchangeService("localhost", 8383)

    # Send tests
    submission_result = service.run_tests("test", "test", Path("criteriaA.dbc.xml"), Path("environmentA.dbe.xml"))

    # Interact with a simulation
    if submission_result and submission_result.submissions:
        for test_name, sid in submission_result.submissions.items():
            ego_requests = ["egoPosition", "egoSpeed", "egoSteeringAngle", "egoFrontCamera", "egoLidar", "egoLaneDist"]
            non_ego_requests = ["nonEgoPosition", "nonEgoSpeed", "nonEgoSteeringAngle", "nonEgoLeftCamera", "nonEgoLidar",
                                "nonEgoLaneDist"]
            ego_vehicle = Thread(target=_handle_vehicle, args=(sid, "ego", ego_requests))
            ego_vehicle.start()
            non_ego_vehicle = Thread(target=_handle_vehicle, args=(sid, "nonEgo", non_ego_requests))
            non_ego_vehicle.start()
            ego_vehicle.join()