env_base.py 6.39 KB
Newer Older
Aravind Bk's avatar
Aravind Bk committed
1 2 3 4 5 6 7 8
from model_checker import Parser


class GymCompliantEnvBase:
    def step(self, action):
        """ Gym compliant step function which
            will be implemented in the subclass.
        """
Ashish Gaurav's avatar
Ashish Gaurav committed
9 10
        raise NotImplemented(self.__class__.__name__ +
                             "step is not implemented.")
Aravind Bk's avatar
Aravind Bk committed
11 12 13 14 15

    def reset(self):
        """ Gym compliant reset function which
            will be implemented in the subclass.
        """
Ashish Gaurav's avatar
Ashish Gaurav committed
16 17
        raise NotImplemented(self.__class__.__name__ +
                             "reset is not implemented.")
Aravind Bk's avatar
Aravind Bk committed
18 19 20 21 22

    def render(self):
        """ Gym compliant step function which
            will be implemented in the subclass.
        """
Ashish Gaurav's avatar
Ashish Gaurav committed
23 24
        raise NotImplemented(self.__class__.__name__ +
                             "render is not implemented.")
Aravind Bk's avatar
Aravind Bk committed
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82


class EpisodicEnvBase(GymCompliantEnvBase):

    # three types possible ('min', 'max', or 'sum');
    # See _reward_superposition below.
    terminal_reward_type = 'max'

    #: If true, the maneuver terminates when the goal has been achieved.
    _terminate_in_goal = False

    #: the reward given at the end of the episode when achieving the goal
    #  (only active when _terminate_in_goal = True).
    _reward_in_goal = 200

    def enable_LTL_preconditions(self):
        self._LTL_preconditions_enable = True

    def disable_LTL_preconditions(self):
        self._LTL_preconditions_enable = False

    @property
    def r_terminal(self):
        return self._r_terminal

    def _init_LTL_preconditions(self):
        """Initialize the LTL preconditions (self._LTL_preconditions)..
            in the subclass.
        """
        return

    def __init__(self):

        #: the set of LTL preconditions that initiate and terminate the envoronment.
        self._LTL_preconditions = list()

        #: If True, then the LTLs in _LTL_preconditions above
        #  determines the termination
        self._LTL_preconditions_enable = True

        #: the atomic proposition for model-checking (initially all False)
        self.__mc_AP = 0

        self._init_LTL_preconditions()

        #: the terminal reward calculated via step;
        # it is not None only when the episode (or maneuver) ends.
        self._r_terminal = None

    def _terminal_reward_superposition(self, r_obs):
        """Calculate the next value when observing "obs," from the prior
           using min, max, or summation depending on the superposition_type.
        """

        if r_obs is None:
            return

        if self.terminal_reward_type == 'min':
Ashish Gaurav's avatar
Ashish Gaurav committed
83 84
            self._r_terminal = r_obs if self._r_terminal is None else min(
                self._r_terminal, r_obs)
Aravind Bk's avatar
Aravind Bk committed
85
        elif self.terminal_reward_type == 'max':
Ashish Gaurav's avatar
Ashish Gaurav committed
86 87
            self._r_terminal = r_obs if self._r_terminal is None else max(
                self._r_terminal, r_obs)
Aravind Bk's avatar
Aravind Bk committed
88 89 90
        elif self.terminal_reward_type == 'sum':
            self._r_terminal = r_obs if self._r_terminal is None else self._r_terminal + r_obs
        else:
Ashish Gaurav's avatar
Ashish Gaurav committed
91 92
            raise AssertionError(
                "The terminal_reward_type has to be 'min', 'max', or 'sum'")
Aravind Bk's avatar
Aravind Bk committed
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126

    def step(self, u):
        # the penalty is a negative reward.
        # So, "penalty" will be summed up to the final reward with its sign
        # reversed, i.e., the reward = - penalty  + (the other reward terms).
        self._r_terminal = None

        if self._LTL_preconditions_enable:
            terminal, info = self._incremental_model_checking()
            if terminal:
                info['episode_termination_reason'] = "LTL_violation"
        else:
            terminal = False
            info = dict()

        if self._terminate_in_goal and self.goal_achieved:
            self._terminal_reward_superposition(self._reward_in_goal)
            terminal = True

        reward = 0 if self._r_terminal is None else self._r_terminal

        return None, reward, terminal, info

    def _incremental_model_checking(self, AP=None):

        if AP is not None:
            self.__mc_AP = int(AP)

        info = dict()
        violate = False
        for LTL_precondition in self._LTL_preconditions:
            if LTL_precondition.enabled:
                LTL_precondition.check_incremental(self.__mc_AP)
                if LTL_precondition.result == Parser.FALSE:
Ashish Gaurav's avatar
Ashish Gaurav committed
127 128
                    self._terminal_reward_superposition(
                        EpisodicEnvBase._reward(LTL_precondition.penalty))
Aravind Bk's avatar
Aravind Bk committed
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
                    violate = True
                    info['ltl_violation'] = LTL_precondition.str
                    # print("\nViolation of \"" + LTL_precondition.str + "\"")

        return violate, info

    def current_model_checking_result(self):
        """Returns whether or not any of the conditions is currently violated."""

        for LTL_precondition in self._LTL_preconditions:
            if LTL_precondition.result == Parser.FALSE:
                return True
        return False

    def _reset_model_checker(self, AP):

        self.__mc_AP = int(AP)

        if self._LTL_preconditions_enable:
            for LTL_precondition in self._LTL_preconditions:
                LTL_precondition.reset_property()
                if LTL_precondition.enabled:
                    LTL_precondition.check_incremental(self.__mc_AP)

    def _set_mc_AP(self, AP):
        self.__mc_AP = int(AP)

    @property
    def termination_condition(self):
        """In the subclass, specify the condition for termination of the episode
           (or the maneuver).
        """
        if self._terminate_in_goal and self.goal_achieved:
            return True

        return self.violation_happened and self._LTL_preconditions_enable

    @property
    def goal_achieved(self):
        """Check whether the ego vehicle achieves the goal of the maneuver or
        not.

        By default, there is no goal, so the ego vehicle never achieves
        it (i.e., goal_achieved is always False).
        """

        return False

    @property
    def violation_happened(self):
        if not self._LTL_preconditions_enable:
            return False

        for LTL_precondition in self._LTL_preconditions:
            if LTL_precondition.result == Parser.FALSE:
                return True
        return False

    # TODO: replace these confusing methods reward and penalty, or not to use both reward and penalty for the property naming.
    @staticmethod
    def _reward(penalty):
        return None if penalty is None else -penalty

    @staticmethod
    def _penalty(reward):
        return None if reward is None else -reward