Skip to main content

ruxla_env/
pendulum.rs

1//! Pendulum, following gymnax's `Pendulum-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 Pendulum episode. The fields are in the order of gymnax's
9/// `EnvState` leaves.
10#[derive(Clone, Debug, Tree)]
11pub struct PendulumState<B: Backend> {
12    /// Steps taken in the episode.
13    pub time: I32<B>,
14    /// The angle of the pendulum (0 is upright).
15    pub theta: F32<B>,
16    /// The angular velocity.
17    pub theta_dot: F32<B>,
18    /// The last torque applied (after clipping).
19    pub last_u: F32<B>,
20}
21
22/// The parameters of Pendulum, in the order of gymnax's `EnvParams` leaves.
23/// Defaults follow `Pendulum-v1`.
24#[derive(Clone, Debug, Tree)]
25pub struct PendulumParams<B: Backend> {
26    /// The time limit.
27    pub max_steps_in_episode: I32<B>,
28    /// The largest angular velocity.
29    pub max_speed: F32<B>,
30    /// The largest torque.
31    pub max_torque: F32<B>,
32    /// The time step.
33    pub dt: F32<B>,
34    /// Gravity.
35    pub g: F32<B>,
36    /// The mass of the pendulum.
37    pub m: F32<B>,
38    /// The length of the pendulum.
39    pub l: F32<B>,
40}
41
42/// gymnax's Pendulum (`Pendulum-v1`): swing up a pendulum and keep it
43/// upright by applying a torque, an action of shape `[1]` in
44/// `[-max_torque, max_torque]` (clipped as gymnax does).
45///
46/// It reproduces gymnax 1.0 with the same operations, so the same keys and
47/// actions give the same trajectories. gymnax computes the step on the
48/// action of shape `[1]` and squeezes the results; here the action is
49/// reshaped to a scalar first (the same values).
50#[derive(Clone, Copy, Debug, Default)]
51pub struct Pendulum;
52
53/// `pi` and `2 pi` as gymnax's `float32` constants.
54const PI: f32 = std::f64::consts::PI as f32;
55const TWO_PI: f32 = (2.0 * std::f64::consts::PI) as f32;
56
57/// gymnax's `angle_normalize`: `((x + pi) % (2 pi)) - pi` with
58/// `jnp.remainder`.
59fn angle_normalize<B: Backend>(x: F32<B>) -> F32<B> {
60    jnp::remainder(x + PI, F32::new(TWO_PI)).to_scalar() - PI
61}
62
63impl Pendulum {
64    fn observation<B: Backend>(&self, s: &PendulumState<B>) -> Array<B, f32> {
65        jnp::stack(&[s.theta.cos(), s.theta.sin(), s.theta_dot], 0)
66    }
67}
68
69impl Environment for Pendulum {
70    type State<B: Backend> = PendulumState<B>;
71    type Params<B: Backend> = PendulumParams<B>;
72    type Obs<B: Backend> = Array<B, f32>;
73    type Action<B: Backend> = Array<B, f32>;
74
75    fn name(&self) -> &str {
76        "Pendulum-v1"
77    }
78
79    fn action_space(&self) -> ActionSpace {
80        ActionSpace::uniform_box(-2.0, 2.0, &[1])
81    }
82
83    fn default_params<B: Backend>(&self) -> PendulumParams<B> {
84        PendulumParams {
85            max_steps_in_episode: I32::new(200),
86            max_speed: F32::new(8.0),
87            max_torque: F32::new(2.0),
88            dt: F32::new(0.05),
89            g: F32::new(10.0),
90            m: F32::new(1.0),
91            l: F32::new(1.0),
92        }
93    }
94
95    fn reset<B: Backend>(
96        &self,
97        key: Key<B>,
98        _params: &PendulumParams<B>,
99    ) -> (Array<B, f32>, PendulumState<B>) {
100        let high = Array::from_slice(&[PI, 1.0], [2]);
101        let init = random::uniform(&key, [2], -&high, high);
102        let state = PendulumState {
103            time: I32::new(0),
104            theta: init.get(0),
105            theta_dot: init.get(1),
106            last_u: F32::new(0.0),
107        };
108        (self.observation(&state), state)
109    }
110
111    fn step_env<B: Backend>(
112        &self,
113        _key: Key<B>,
114        s: &PendulumState<B>,
115        action: Array<B, f32>,
116        p: &PendulumParams<B>,
117    ) -> Transition<B, PendulumState<B>, Array<B, f32>> {
118        let u = action
119            .reshape([])
120            .to_scalar()
121            .clamp(-p.max_torque, p.max_torque);
122        let reward = -(angle_normalize(s.theta).integer_pow(2)
123            + 0.1 * s.theta_dot.integer_pow(2)
124            + 0.001 * u.integer_pow(2));
125        let newthdot = s.theta_dot
126            + (3.0 * p.g / (2.0 * p.l) * s.theta.sin() + 3.0 / (p.m * p.l.integer_pow(2)) * u)
127                * p.dt;
128        let newthdot = newthdot.clamp(-p.max_speed, p.max_speed);
129        let newth = s.theta + newthdot * p.dt;
130        let state = PendulumState {
131            time: s.time + 1,
132            theta: newth,
133            theta_dot: newthdot,
134            last_u: u,
135        };
136        Transition {
137            obs: self.observation(&state),
138            state,
139            reward,
140            terminated: Bool::new(false),
141        }
142    }
143
144    fn step_env_uses_key(&self) -> bool {
145        false
146    }
147
148    fn is_truncated<B: Backend>(&self, s: &PendulumState<B>, p: &PendulumParams<B>) -> Bool<B> {
149        s.time.ge(p.max_steps_in_episode)
150    }
151}