Ejemplo n.º 1
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
Ejemplo n.º 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
Ejemplo n.º 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))

            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
Ejemplo n.º 4
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
Ejemplo n.º 5
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