Skip to main content

ruxla_env/
cartpole.rs

1//! CartPole, following gymnax's `CartPole-v1`.
2
3use ruxla_core::random::{self, Key};
4use ruxla_core::{Array, Backend, Bool, F32, I32, Tree, jnp};
5
6use crate::{ActionSpace, Environment, Transition};
7
8/// The state of a CartPole episode. The fields are in the order of gymnax's
9/// `EnvState` leaves.
10#[derive(Clone, Debug, Tree)]
11pub struct CartPoleState<B: Backend> {
12    /// Steps taken in the episode.
13    pub time: I32<B>,
14    /// Cart position.
15    pub x: F32<B>,
16    /// Cart velocity.
17    pub x_dot: F32<B>,
18    /// Pole angle.
19    pub theta: F32<B>,
20    /// Pole angular velocity.
21    pub theta_dot: F32<B>,
22}
23
24/// The parameters of CartPole. Defaults follow `CartPole-v1`.
25#[derive(Clone, Debug, Tree)]
26pub struct CartPoleParams<B: Backend> {
27    /// Gravity.
28    pub gravity: F32<B>,
29    /// Mass of the cart.
30    pub masscart: F32<B>,
31    /// Mass of the pole.
32    pub masspole: F32<B>,
33    /// `masscart + masspole`.
34    pub total_mass: F32<B>,
35    /// Half the length of the pole.
36    pub length: F32<B>,
37    /// `masspole * length`.
38    pub polemass_length: F32<B>,
39    /// The force of an action.
40    pub force_mag: F32<B>,
41    /// The time step.
42    pub tau: F32<B>,
43    /// The angle at which the episode terminates.
44    pub theta_threshold_radians: F32<B>,
45    /// The position at which the episode terminates.
46    pub x_threshold: F32<B>,
47    /// The time limit.
48    pub max_steps_in_episode: I32<B>,
49}
50
51/// gymnax's CartPole (`CartPole-v1`): balance a pole on a cart by pushing it
52/// left (action 0) or right (action 1).
53///
54/// The dynamics, rewards, termination, and resets reproduce gymnax 1.0 with
55/// the same operations, so the same keys and actions give the same
56/// trajectories, and the traced IR has the form of gymnax's jaxpr.
57#[derive(Clone, Copy, Debug, Default)]
58pub struct CartPole;
59
60impl CartPole {
61    fn observation<B: Backend>(&self, s: &CartPoleState<B>) -> Array<B, f32> {
62        jnp::stack(&[s.x, s.x_dot, s.theta, s.theta_dot], 0)
63    }
64
65    fn is_terminated<B: Backend>(&self, s: &CartPoleState<B>, p: &CartPoleParams<B>) -> Bool<B> {
66        let done1 = s.x.lt(-p.x_threshold) | s.x.gt(p.x_threshold);
67        let done2 = s.theta.lt(-p.theta_threshold_radians) | s.theta.gt(p.theta_threshold_radians);
68        done1 | done2
69    }
70}
71
72impl Environment for CartPole {
73    type State<B: Backend> = CartPoleState<B>;
74    type Params<B: Backend> = CartPoleParams<B>;
75    type Obs<B: Backend> = Array<B, f32>;
76    type Action<B: Backend> = I32<B>;
77
78    fn name(&self) -> &str {
79        "CartPole-v1"
80    }
81
82    fn action_space(&self) -> ActionSpace {
83        ActionSpace::Discrete(2)
84    }
85
86    fn default_params<B: Backend>(&self) -> CartPoleParams<B> {
87        CartPoleParams {
88            gravity: F32::new(9.8),
89            masscart: F32::new(1.0),
90            masspole: F32::new(0.1),
91            total_mass: F32::new((1.0f64 + 0.1) as f32),
92            length: F32::new(0.5),
93            polemass_length: F32::new(0.05),
94            force_mag: F32::new(10.0),
95            tau: F32::new(0.02),
96            theta_threshold_radians: F32::new((12.0 * 2.0 * std::f64::consts::PI / 360.0) as f32),
97            x_threshold: F32::new(2.4),
98            max_steps_in_episode: I32::new(500),
99        }
100    }
101
102    fn reset<B: Backend>(
103        &self,
104        key: Key<B>,
105        _params: &CartPoleParams<B>,
106    ) -> (Array<B, f32>, CartPoleState<B>) {
107        let init = random::uniform(&key, [4], -0.05f32, 0.05f32);
108        let part = |i: i64| init.i(i).to_scalar();
109        let state = CartPoleState {
110            time: I32::new(0),
111            x: part(0),
112            x_dot: part(1),
113            theta: part(2),
114            theta_dot: part(3),
115        };
116        (self.observation(&state), state)
117    }
118
119    fn step_env<B: Backend>(
120        &self,
121        _key: Key<B>,
122        s: &CartPoleState<B>,
123        action: I32<B>,
124        p: &CartPoleParams<B>,
125    ) -> Transition<B, CartPoleState<B>, Array<B, f32>> {
126        let prev_terminal = self.is_terminated(s, p);
127        // As in gymnax, `1 - action` is computed on integers.
128        let force = p.force_mag * action.cast::<f32>() - p.force_mag * (1 - action).cast::<f32>();
129        let costheta = s.theta.cos();
130        let sintheta = s.theta.sin();
131        let temp =
132            (force + p.polemass_length * s.theta_dot.integer_pow(2) * sintheta) / p.total_mass;
133        let thetaacc = (p.gravity * sintheta - costheta * temp)
134            / (p.length
135                * ((4.0f64 / 3.0) as f32 - p.masspole * costheta.integer_pow(2) / p.total_mass));
136        let xacc = temp - p.polemass_length * thetaacc * costheta / p.total_mass;
137        let next = CartPoleState {
138            time: s.time + 1,
139            x: s.x + p.tau * s.x_dot,
140            x_dot: s.x_dot + p.tau * xacc,
141            theta: s.theta + p.tau * s.theta_dot,
142            theta_dot: s.theta_dot + p.tau * thetaacc,
143        };
144        // The reward depends on whether the previous state was terminal.
145        let reward = 1.0 - prev_terminal.cast::<f32>();
146        let terminated = self.is_terminated(&next, p);
147        Transition {
148            obs: self.observation(&next),
149            state: next,
150            reward,
151            terminated,
152        }
153    }
154
155    fn step_env_uses_key(&self) -> bool {
156        false
157    }
158
159    fn is_truncated<B: Backend>(&self, s: &CartPoleState<B>, p: &CartPoleParams<B>) -> Bool<B> {
160        s.time.ge(p.max_steps_in_episode)
161    }
162}