|
| 1 | +"""What the environment does with an action it cannot use. |
| 2 | +
|
| 3 | +A policy that diverges emits NaN, and it is the most ordinary failure there is |
| 4 | +while training one. Measured on the pin these tests were written against: a |
| 5 | +single NaN in `tvc` was harmless, the run finished with the same score as a |
| 6 | +clean one, while a NaN in `launch_inclination_heading` raised |
| 7 | +`ValueError: All components of the initial state y0 must be finite` and ended |
| 8 | +the evaluation. ActiveRocketPy #19 makes the actuator setters refuse a |
| 9 | +non-finite command too, so without this the first kind becomes the second. |
| 10 | +
|
| 11 | +The rule here is that a field the environment cannot use is dropped, the |
| 12 | +actuator keeps what it holds, and the episode carries on. A run is not lost to |
| 13 | +one bad step. |
| 14 | +""" |
| 15 | + |
| 16 | +import logging |
| 17 | +import unittest |
| 18 | +from importlib.util import find_spec |
| 19 | + |
| 20 | +import numpy as np |
| 21 | + |
| 22 | +_STACK_AVAILABLE = find_spec("rocketpy") is not None |
| 23 | + |
| 24 | +if _STACK_AVAILABLE: |
| 25 | + from BalloonPoppingGymEnv.envs.balloon_world import ( |
| 26 | + BalloonPoppingEnv, |
| 27 | + check_action, |
| 28 | + ) |
| 29 | + from BalloonPoppingGymEnv.evaluation.evaluate import load_scenario_parameters |
| 30 | + |
| 31 | +SCENARIO = 0 |
| 32 | +LAUNCH_STEP = 1 |
| 33 | +STEPS_AFTER_LAUNCH = 8 |
| 34 | + |
| 35 | + |
| 36 | +_CLEAN = { |
| 37 | + "launch_inclination_heading": np.array([80.0, 0.0]), |
| 38 | + "tvc": np.array([0.0, 0.0]), |
| 39 | + "roll": np.array([0.0]), |
| 40 | + "throttle": np.array([1.0]), |
| 41 | +} |
| 42 | + |
| 43 | + |
| 44 | +class TestWhichFieldsAreUnusable(unittest.TestCase): |
| 45 | + """The reader, tested on its own because everything below trusts it.""" |
| 46 | + |
| 47 | + def test_a_clean_action_has_none(self): |
| 48 | + self.assertEqual(check_action(dict(_CLEAN)), []) |
| 49 | + |
| 50 | + def test_each_field_is_found_by_name(self): |
| 51 | + for field, shape in ( |
| 52 | + ("launch_inclination_heading", 2), |
| 53 | + ("tvc", 2), |
| 54 | + ("roll", 1), |
| 55 | + ("throttle", 1), |
| 56 | + ): |
| 57 | + with self.subTest(field=field): |
| 58 | + action = dict(_CLEAN, **{field: np.full(shape, np.nan)}) |
| 59 | + |
| 60 | + self.assertEqual(check_action(action), [field]) |
| 61 | + |
| 62 | + def test_infinity_counts_too(self): |
| 63 | + """`np.clip` would carry an infinity straight through, and the actuator |
| 64 | + would store it, so it is not only NaN that has to be caught.""" |
| 65 | + action = dict(_CLEAN, tvc=np.array([np.inf, 0.0])) |
| 66 | + |
| 67 | + self.assertEqual(check_action(action), ["tvc"]) |
| 68 | + |
| 69 | + def test_a_field_that_is_not_a_number_at_all(self): |
| 70 | + """`np.asarray(..., dtype=float)` raises on these rather than giving a |
| 71 | + NaN, so they need naming separately or they reach the actuator.""" |
| 72 | + for value in ("nope", None, {"x": 1}): |
| 73 | + with self.subTest(value=repr(value)): |
| 74 | + self.assertIn("roll", check_action(dict(_CLEAN, roll=value))) |
| 75 | + |
| 76 | + def test_a_missing_field_is_not_usable(self): |
| 77 | + """Every shipped agent returns all four, and `step()` indexes them, so a |
| 78 | + partial action passing the helper and failing in the environment is the |
| 79 | + split this exists to remove.""" |
| 80 | + self.assertEqual( |
| 81 | + check_action({"roll": np.array([0.0])}), |
| 82 | + ["launch_inclination_heading", "throttle", "tvc"], |
| 83 | + ) |
| 84 | + |
| 85 | + def test_the_wrong_number_of_values_is_not_usable(self): |
| 86 | + """An empty array passes a finiteness test on its own, and `step()` |
| 87 | + indexes `tvc[1]`.""" |
| 88 | + for field, value in ( |
| 89 | + ("tvc", np.array([])), |
| 90 | + ("tvc", np.zeros(3)), |
| 91 | + ("tvc", 0.0), |
| 92 | + ("launch_inclination_heading", np.array([80.0])), |
| 93 | + ): |
| 94 | + with self.subTest(field=field, size=np.size(value)): |
| 95 | + self.assertIn(field, check_action(dict(_CLEAN, **{field: value}))) |
| 96 | + |
| 97 | + |
| 98 | +@unittest.skipUnless(_STACK_AVAILABLE, "simulation stack not installed") |
| 99 | +class TestAnActionTheEnvironmentCannotUse(unittest.TestCase): |
| 100 | + @classmethod |
| 101 | + def setUpClass(cls): |
| 102 | + cls.parameters, _given = load_scenario_parameters(SCENARIO) |
| 103 | + |
| 104 | + def _fresh(self): |
| 105 | + env = BalloonPoppingEnv(render_mode=None, parameters=self.parameters) |
| 106 | + env.reset(seed=self.parameters["scenario"]["random_seed"]) |
| 107 | + return env |
| 108 | + |
| 109 | + @staticmethod |
| 110 | + def _action(env, launch=False): |
| 111 | + action = env.action_space.sample() |
| 112 | + action["launch"] = np.array(int(launch), dtype=action["launch"].dtype) |
| 113 | + action["launch_inclination_heading"] = np.array([80.0, 0.0], dtype=np.float64) |
| 114 | + action["throttle"] = np.ones_like(action["throttle"]) |
| 115 | + action["tvc"] = np.zeros_like(action["tvc"]) |
| 116 | + action["roll"] = np.zeros_like(action["roll"]) |
| 117 | + return action |
| 118 | + |
| 119 | + def _flown(self, env, steps, corrupt=None): |
| 120 | + """Launch, then step, optionally corrupting one field throughout.""" |
| 121 | + for index in range(LAUNCH_STEP + steps): |
| 122 | + action = self._action(env, launch=index == LAUNCH_STEP - 1) |
| 123 | + if corrupt and index >= LAUNCH_STEP: |
| 124 | + action[corrupt] = np.full_like( |
| 125 | + np.asarray(action[corrupt], dtype=float), np.nan |
| 126 | + ) |
| 127 | + env.step(action) |
| 128 | + return env |
| 129 | + |
| 130 | + def test_a_control_field_of_nans_does_not_end_the_run(self): |
| 131 | + """The case ActiveRocketPy #19 turns into a ValueError without this.""" |
| 132 | + for field in ("tvc", "roll", "throttle"): |
| 133 | + with self.subTest(field=field): |
| 134 | + env = self._flown(self._fresh(), STEPS_AFTER_LAUNCH, corrupt=field) |
| 135 | + |
| 136 | + self.assertTrue(env.rocket_launched) |
| 137 | + self.assertEqual( |
| 138 | + len(env.trajectories), LAUNCH_STEP + STEPS_AFTER_LAUNCH |
| 139 | + ) |
| 140 | + |
| 141 | + def test_the_actuator_keeps_the_value_it_had(self): |
| 142 | + """Dropping the command has to mean keeping the last one, not zeroing |
| 143 | + it, or a single NaN would silently cut the throttle.""" |
| 144 | + env = self._fresh() |
| 145 | + for index in range(4): |
| 146 | + env.step(self._action(env, launch=index == LAUNCH_STEP - 1)) |
| 147 | + held = float(env._rocket_flight.rocket.throttle_control.throttle) |
| 148 | + |
| 149 | + action = self._action(env) |
| 150 | + action["throttle"] = np.full_like( |
| 151 | + np.asarray(action["throttle"], dtype=float), np.nan |
| 152 | + ) |
| 153 | + env.step(action) |
| 154 | + |
| 155 | + self.assertEqual( |
| 156 | + float(env._rocket_flight.rocket.throttle_control.throttle), held |
| 157 | + ) |
| 158 | + |
| 159 | + def test_a_launch_attitude_of_nans_does_not_launch(self): |
| 160 | + """There is no previous attitude to fall back on, so the launch is |
| 161 | + refused rather than dropped. Measured without this: the flight is built |
| 162 | + from a NaN quaternion and raises out of the integrator.""" |
| 163 | + env = self._fresh() |
| 164 | + action = self._action(env, launch=True) |
| 165 | + action["launch_inclination_heading"] = np.array([np.nan, 0.0]) |
| 166 | + |
| 167 | + env.step(action) |
| 168 | + |
| 169 | + self.assertFalse(env.rocket_launched) |
| 170 | + |
| 171 | + def test_the_agent_can_launch_on_a_later_step(self): |
| 172 | + """The half that stops the refusal above being a way to lose the run.""" |
| 173 | + env = self._fresh() |
| 174 | + broken = self._action(env, launch=True) |
| 175 | + broken["launch_inclination_heading"] = np.array([np.nan, 0.0]) |
| 176 | + env.step(broken) |
| 177 | + |
| 178 | + env.step(self._action(env, launch=True)) |
| 179 | + |
| 180 | + self.assertTrue(env.rocket_launched) |
| 181 | + |
| 182 | + def test_the_dropped_field_is_named_in_the_log(self): |
| 183 | + """A competitor reading the output has to be able to tell that a command |
| 184 | + went nowhere, and which one.""" |
| 185 | + env = self._fresh() |
| 186 | + for index in range(3): |
| 187 | + env.step(self._action(env, launch=index == LAUNCH_STEP - 1)) |
| 188 | + action = self._action(env) |
| 189 | + action["tvc"] = np.full_like(np.asarray(action["tvc"], dtype=float), np.nan) |
| 190 | + |
| 191 | + with self.assertLogs( |
| 192 | + "BalloonPoppingGymEnv.envs.balloon_world", logging.WARNING |
| 193 | + ) as caught: |
| 194 | + env.step(action) |
| 195 | + |
| 196 | + self.assertIn("tvc", "".join(caught.output)) |
| 197 | + |
| 198 | + def test_a_clean_run_logs_nothing_and_scores_the_same(self): |
| 199 | + """The half that stops all of this being satisfied by dropping |
| 200 | + everything.""" |
| 201 | + env = self._fresh() |
| 202 | + logger = logging.getLogger("BalloonPoppingGymEnv.envs.balloon_world") |
| 203 | + with self.assertNoLogs(logger, logging.WARNING): |
| 204 | + for index in range(LAUNCH_STEP + STEPS_AFTER_LAUNCH): |
| 205 | + env.step(self._action(env, launch=index == LAUNCH_STEP - 1)) |
| 206 | + |
| 207 | + self.assertTrue(env.rocket_launched) |
| 208 | + |
| 209 | + |
| 210 | +if __name__ == "__main__": |
| 211 | + unittest.main() |
0 commit comments