コード例 #1
0
def test_decode_server_message():
    buffer = b'(angle 0.008838)' \
             b'(curLapTime 4.052)' \
             b'(damage 0)' \
             b'(distFromStart 1015.56)' \
             b'(distRaced 42.6238)' \
             b'(fuel 93.9356)' \
             b'(gear 3)' \
             b'(lastLapTime 0)' \
             b'(opponents 123.4 200 200 200 200 200 200 200 200 200 200 200 200 200 200 200 200 200' \
             b' 200 200 200 200 200 200 200 200 200 200 200 200 200 200 200 200 200 200)' \
             b'(racePos 1)' \
             b'(rpm 4509.31)' \
             b'(speedX 81.5135)' \
             b'(speedY 0.40771)' \
             b'(speedZ -2.4422)' \
             b'(track 4.3701 4.52608 5.02757 6.07753 8.25773 11.1429 13.451 16.712 21.5022' \
             b' 30.2855 51.8667 185.376 69.9077 26.6353 12.6621 8.2019 6.5479 5.82979 5.63029)' \
             b'(trackPos 0.126012)' \
             b'(wheelSpinVel 67.9393 68.8267 71.4009 71.7363)' \
             b'(z 0.336726)' \
             b'(focus 26.0077 27.9798 30.2855 33.0162 36.3006)'

    d = Serializer().decode(buffer)

    assert len(d) == 19
    assert d['angle'] == '0.008838'
    assert d['wheelSpinVel'] == ['67.9393', '68.8267', '71.4009', '71.7363']

    c = CarState(d)

    assert c.angle == 0.5063800993366215
    assert c.current_lap_time == 4.052
    assert c.damage == 0
    assert c.distance_from_start == 1015.56
    assert c.distance_raced == 42.6238
    assert c.fuel == 93.9356
    assert c.gear == 3
    assert c.last_lap_time == 0.0
    assert c.opponents == (123.4, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200,
                           200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200,
                           200, 200, 200, 200, 200, 200, 200, 200)
    assert c.race_position == 1
    assert c.rpm == 4509.31
    assert c.speed_x == 22.64263888888889
    assert c.speed_y == 0.11325277777777779
    assert c.speed_z == -0.6783888888888889
    assert c.distances_from_edge == (4.3701, 4.52608, 5.02757, 6.07753, 8.25773, 11.1429, 13.451,
                                     16.712, 21.5022, 30.2855, 51.8667, 185.376, 69.9077, 26.6353,
                                     12.6621, 8.2019, 6.5479, 5.82979, 5.63029)
    assert c.distance_from_center == 0.126012
    assert c.wheel_velocities == (3892.635153073154, 3943.4794278130635, 4090.970223435639,
                                  4110.1872278843275)
    assert c.z == 0.336726
    assert c.focused_distances_from_edge == (26.0077, 27.9798, 30.2855, 33.0162, 36.3006)
    assert c.focused_distances_from_egde_valid

    # fake bad focus value:
    c.focused_distances_from_edge = (-1.0, -1.0, -1.0, -1.0, -1.0)
    assert not c.focused_distances_from_egde_valid
コード例 #2
0
    def drive(self, carstate: State) -> Command:

        print('Drive')
        input = carstate.to_input_array()

        if np.isnan(input).any():
            if not self.stopped:
                self.saveResults()

            print(input)
            print('NaN INPUTS!!! STOP WORKING')
            return Command()

        self.stopped = np.isnan(input).any()

        self.print_log(carstate)

        self.update(carstate)

        try:
            output = self.net.activate(input)
            command = Command()

            if self.unstuck and self.isStuck(carstate):
                print('Ops! I got STUCK!!!')
                self.reverse(carstate, command)

            else:

                if self.unstuck and carstate.gear <= 0:
                    carstate.gear = 1

                for i in range(len(output)):
                    if np.isnan(output[i]):
                        output[i] = 0.0

                print('Out = ' + str(output))

                self.accelerate(output[0], output[1], 0, carstate, command)

                if len(output) == 3:
                    # use this if the steering is just one output
                    self.steer(output[2], 0, carstate, command)
                else:
                    # use this command if there are 2 steering outputs
                    self.steer(output[2], output[3], carstate, command)
        except:
            print('Error!')
            self.saveResults()
            raise

        if self.data_logger:
            self.data_logger.log(carstate, command)

        return command
コード例 #3
0
    def step(self, carstate: State, command: Command):

        if carstate.gear <= 0:
            carstate.gear = 1

        input = self.processInput(carstate)

        if np.isnan(input).any():
            return False

        try:
            output = self.model.activate(input)

            for i in range(len(output)):
                if np.isnan(output[i]):
                    output[i] = 0.0

            print('Out = ' + str(output))

            self.accelerate(output[0], output[1], carstate, command)

            if len(output) == 3:
                # use this if the steering is just one output
                self.steer(output[2], 0, carstate, command)
            else:
                # use this command if there are 2 steering outputs
                self.steer(output[2], output[3], carstate, command)

        except:
            print('Error!')
            raise

        return True
コード例 #4
0
    def drive(self, carstate: State) -> Command:
        """ Description

        Args:
            carstate:   All parameters packed in a State object

        Returns:
            command:    The next move packed in a Command object

        """
        self.iter += 1
        self.back_up_driver.update_status(carstate)

        # trackers
        self.update_trackers(carstate)
        if PRINT_STATE:  # and (self.iter % PRINT_CYCLE_INTERVAL) == 0:
            self.print_trackers(carstate, r=True)

        # crash and collision detection for swarm
        if ENABLE_SWARM:
            if self.back_up_driver.needs_help or self.back_up_driver.is_off_road:
                self.crashed_in_last_frame = True
                if not self.crashed_in_last_frame:
                    debug(self.iter, "SWARM:  crashed")
            for dist in carstate.opponents:
                if dist == 0:
                    self.contact_in_last_frame = True

        # crisis handling
        if ENABLE_CRISIS_DRIVER:
            if self.back_up_driver.is_in_control:
                return self.back_up_driver.drive(carstate)
            elif self.back_up_driver.needs_help:
                self.back_up_driver.pass_control(carstate)
                return self.back_up_driver.drive(carstate)

        # since the data and python's values differ we need to adjust them
        try:
            carstate.angle = radians(carstate.angle)
            carstate.speed_x = carstate.speed_x * 3.6
            command = self.make_next_command(carstate)
        except Exception as e:
            err(self.iter, str(e))
            command = self.back_up_driver.driver.drive(carstate)

        return command
コード例 #5
0
    def drive(self, carstate: State) -> Command:
        self.update_trackers(carstate)
        if self.in_a_bad_place(carstate):
            command = self.back_up_driver.drive(carstate)
            if self.bad_counter >= 600 and is_stuck(carstate):
                # we try reversing
                command.gear = -command.gear
                if command.gear < 0:
                    command.steering = -command.steering
                    command.gear = -1
                self.bad_counter = 200
        else:
            # since the data and python's values differ we need to adjust them
            carstate.angle = math.radians(carstate.angle)
            carstate.speed_x = carstate.speed_x*3.6
            command = self.make_next_command(carstate)
            # based on target, implement speed/steering manually
        print("Executing command: gear={}, acc={}, break={}, steering={}".format(command.gear,
                                                                                 command.accelerator,
                                                                                 command.brake,
                                                                                 command.steering))

        return command
コード例 #6
0
def dataToStateExtended(data) -> State:
    datalist = list(data)
    state = State({
        'angle':
        datalist[0],
        'curLapTime':
        0,
        'damage':
        0,
        'distFromStart':
        0,
        'distRaced':
        0,
        'fuel':
        0,
        'gear':
        0,
        'lastLapTime':
        0,
        'opponents': {},
        'racePos':
        0,
        'rpm':
        0,
        'speedX':
        datalist[1],
        'speedY':
        datalist[2],
        'speedZ':
        datalist[3],
        'track':
        datalist[4:23],
        'trackPos':
        datalist[23],
        'wheelSpinVel': (
            datalist[24],
            datalist[25],
            datalist[26],
            datalist[27],
        ),
        'z':
        datalist[28],
        'focus':
        (datalist[29], datalist[30], datalist[31], datalist[32], datalist[33])
    })
    return state
コード例 #7
0
    def drive(self, carstate: State) -> Command:
        """
        Produces driving command in response to newly received car state.

        This is a dummy driving routine, very dumb and not really considering a
        lot of inputs. But it will get the car (if not disturbed by other
        drivers) successfully driven along the race track.
        """
        print('Drive')
        input = carstate.to_input_array()

        self.distance = carstate.distance_raced
        if self.curr_time > carstate.current_lap_time:
            self.time += carstate.last_lap_time

        self.curr_time = carstate.current_lap_time

        try:
            output = self.model.step(input)

            for i in range(len(output)):
                output[i] = max(0, output[i])

            print('Out = ' + str(output))

            command = Command()

            self.accelerate(output[0], output[1], carstate, command)
            self.steer(output[2], output[3], carstate, command)

            # self.steer(carstate, 0.0, command)
            #
            # v_x = min(output[0], 300)
            #
            # self.accelerate(carstate, v_x, command)

        except OverflowError as err:
            print('--------- OVERFLOW! ---------')
            self.saveResults()
            raise err

        if self.data_logger:
            self.data_logger.log(carstate, command)

        return command
コード例 #8
0
    def step(self, carstate: State, command: Command):

        if carstate.gear <= 0:
            carstate.gear = 1

        input = self.processInput(carstate)

        if np.isnan(input).any():
            return False

        try:
            output = self.model.activate(input)

            for i in range(len(output)):
                if np.isnan(output[i]):
                    output[i] = 0.0

            print('Out = ' + str(output))

            accelerator = 0
            brake = 0

            if len(output) == 2:
                if output[0] > 0:
                    accelerator = output[0]
                else:
                    brake = -1 * output[0]
            else:
                accelerator = output[0]
                brake = output[1]

            self.accelerate(accelerator, brake, carstate, command)
            self.steer(output[-1], 0, carstate, command)

        except:
            print('Error!')
            raise

        return True
コード例 #9
0
def dataToState(data) -> State:
    datalist = list(data)
    state = State({
        'angle': datalist[2] / DEGREE_PER_RADIANS,
        'curLapTime': 0,
        'damage': 0,
        'distFromStart': 0,
        'distRaced': 0,
        'fuel': 0,
        'gear': 0,
        'lastLapTime': 0,
        'opponents': {},
        'racePos': 0,
        'rpm': 0,
        'speedX': datalist[0] / MPS_PER_KMH,
        'speedY': 0,
        'speedZ': 0,
        'track': datalist[3:22],
        'trackPos': datalist[1],
        'wheelSpinVel': (0, 0),
        'z': 0,
        'focus': (0, 0)
    })
    return state
コード例 #10
0
    def drive(self, carstate: State) -> Command:
        if not self.race_started and carstate.distance_from_start < 3:
            self.race_started = True
            try:
                position_team = int(open("mjv_partner1.txt", 'r').read())
                open("mjv_partner2.txt", 'w').write(str(carstate.race_position))
                self.number = 2
                self.partner = 1
            except:
                open("mjv_partner1.txt", "w").write(str(carstate.race_position))
                self.number = 1
                self.partner = 2
        elif self.race_started:
            position_other = int(open("mjv_partner{}.txt".format(self.partner), 'r').read())
            open("mjv_partner{}.txt".format(self.number), "w").write(str(carstate.race_position))
            if carstate.race_position > position_other:
                self.leader = False
            else:
                self.leader = True

        # print("Distance: {}".format(carstate.distance_from_start))
        # Select the sensors we need for our model

        self.speeds.append(carstate.speed_x)

        command = Command()
        distances = list(carstate.distances_from_edge)
        sensors = [carstate.speed_x, carstate.distance_from_center,
                   carstate.angle, *(carstate.distances_from_edge)]
        # CRASHED
        off_road = all(distance == -1.0 for distance in distances)
        standing_still = self.recovers == 0 and all(abs(s) < 1.0 for s in self.speeds[-5:])
        if self.race_started and (off_road or self.recovers > 0):
            command = self.recover(carstate, command)
        # NOT CRASHED
        else:
            if carstate.gear == -1:
                carstate.gear = 2
            if self.norm:
                # Sensor normalization -> ?
                sensors = self.normalize_sensors(sensors)

            # Forward pass our model
            y = self.model(Variable(torch.Tensor(sensors)))
            # Create command from model output

            command.accelerator = np.clip(y.data[0], 0, 1)
            command.brake = np.clip(y.data[1], 0, 1)
            command.steering = np.clip(y.data[2], -1, 1)

            if self.race_started and self.is_leader and carstate.distance_from_start > 50: # TODO include not leader
                command = self.helper.drive(command, distances, carstate)

            # Naive switching of gear
            self.switch_gear(carstate, command)

        # print("Accelerate: {}".format(command.accelerator))
        # print("Brake:      {}".format(command.brake))
        # print("Steer:      {}".format(command.steering))

        if self.record is True:
            sensor_string = ",".join([str(x) for x in sensors]) + "\n"
            self.file_handler.write(str(y.data[0]) + "," + str(y.data[1]) + "," + str(y.data[2]) + "," + sensor_string)
        return command
コード例 #11
0
ファイル: neural_net.py プロジェクト: tharangni/slowbro-1
 s = State({
     'angle':
     '0.008838',
     'wheelSpinVel': ['67.9393', '68.8267', '71.4009', '71.7363'],
     'rpm':
     '4509.31',
     'focus': ['26.0077', '27.9798', '30.2855', '33.0162', '36.3006'],
     'trackPos':
     '0.126012',
     'fuel':
     '93.9356',
     'speedX':
     '81.5135',
     'speedZ':
     '-2.4422',
     'track': [
         '4.3701', '4.52608', '5.02757', '6.07753', '8.25773', '11.1429',
         '13.451', '16.712', '21.5022', '30.2855', '51.8667', '185.376',
         '69.9077', '26.6353', '12.6621', '8.2019', '6.5479', '5.82979',
         '5.63029'
     ],
     'gear':
     '3',
     'damage':
     '0',
     'distRaced':
     '42.6238',
     'z':
     '0.336726',
     'racePos':
     '1',
     'speedY':
     '0.40771',
     'curLapTime':
     '4.052',
     'lastLapTime':
     '0',
     'distFromStart':
     '1015.56',
     'opponents': [
         '123.4', '200', '200', '200', '200', '200', '200', '200', '200',
         '200', '200', '200', '200', '200', '200', '200', '200', '200',
         '200', '200', '200', '200', '200', '200', '200', '200', '200',
         '200', '200', '200', '200', '200', '200', '200', '200', '200'
     ]
 })
コード例 #12
0
    def drive(self, carstate: State) -> Command:
        if carstate.distance_raced < 3:
            try:
                self.dict["position"] = carstate.race_position
                with open("mjv_partner{}.txt".format(self.port),
                          "wb") as handle:
                    pickle.dump(self.dict,
                                handle,
                                protocol=pickle.HIGHEST_PROTOCOL)
            except:
                pass
            path = os.path.abspath(os.path.dirname(__file__))
            for i in os.listdir(path):
                if os.path.isfile(os.path.join(
                        path,
                        i)) and 'mjv_partner' in i and not str(self.port) in i:
                    self.partner = i.strip('mjv_partner').strip('.txt')
        else:
            self.race_started = True

            try:
                with open("mjv_partner{}.txt".format(self.partner),
                          'rb') as handle:
                    self.dict_teammate = pickle.load(handle)

                self.dict["position"] = carstate.race_position
                with open("mjv_partner{}.txt".format(self.port),
                          "wb") as handle:
                    pickle.dump(self.dict,
                                handle,
                                protocol=pickle.HIGHEST_PROTOCOL)
                # print(self.port, self.dict_teammate["position"])
                # print("RESULT", carstate.race_position > int(self.dict_teammate["position"]))
                if carstate.race_position > int(
                        self.dict_teammate["position"]):
                    self.is_leader = False
                else:
                    self.is_leader = True
            except:
                print("Not able to read port", self.port)
                pass

            # print(self.dict_teammate)
            # print(self.port, self.leader)

        # print("Distance: {}".format(carstate.distance_from_start))
        # Select the sensors we need for our model

        self.speeds.append(carstate.speed_x)

        command = Command()
        distances = list(carstate.distances_from_edge)
        sensors = [
            carstate.speed_x, carstate.distance_from_center, carstate.angle,
            *(carstate.distances_from_edge)
        ]
        # CRASHED
        off_road = all(distance == -1.0 for distance in distances)

        standing_still = self.recovers == 0 and all(
            abs(s) < 1.0 for s in self.speeds[-5:])
        if self.race_started and (off_road or self.recovers > 0):
            command = self.recover(carstate, command)

            if not self.crash_recorded:
                self.crash_recorded = True
                self.dict["crashes"].append(carstate.distance_raced)

        # NOT CRASHED
        else:
            self.crash_recorded = False

            if carstate.gear == -1:
                carstate.gear = 2
            if self.norm:
                # Sensor normalization -> ?
                sensors = self.normalize_sensors(sensors)

            # Forward pass our model
            y = self.model(Variable(torch.Tensor(sensors)))[0]
            # Create command from model output

            command.accelerator = np.clip(y.data[0], 0, 1)
            command.brake = np.clip(y.data[1], 0, 1)
            command.steering = np.clip(y.data[2], -1, 1)

            command = self.smooth_commands(command)

            # print(self.race_started and not self.is_leader)
            # print("LEADER", self.is_leader)
            if self.race_started and not self.is_leader and carstate.distance_from_start > 50:
                command = self.check_swarm(command, carstate)

            # Naive switching of gear
            self.switch_gear(carstate, command)

        # print("Accelerate: {}".format(command.accelerator))
        # print("Brake:      {}".format(command.brake))
        # print("Steer:      {}".format(command.steering))

        if self.record is True:
            sensor_string = ",".join([str(x) for x in sensors]) + "\n"
            self.file_handler.write(
                str(y.data[0]) + "," + str(y.data[1]) + "," + str(y.data[2]) +
                "," + sensor_string)
        return command