Skip to main content

ruxla_env/
acrobot.rs

1//! Acrobot, following gymnax's `Acrobot-v1`.
2
3use ruxla_core::random::{self, Key};
4use ruxla_core::{Array, Backend, Bool, F32, I32, Tree, jnp, lax};
5
6use crate::{ActionSpace, Environment, Transition};
7
8/// The state of an Acrobot episode. The fields are in the order of gymnax's
9/// `EnvState` leaves.
10#[derive(Clone, Debug, Tree)]
11pub struct AcrobotState<B: Backend> {
12    /// Steps taken in the episode.
13    pub time: I32<B>,
14    /// The angle of the first link.
15    pub joint_angle1: F32<B>,
16    /// The angle of the second link, relative to the first.
17    pub joint_angle2: F32<B>,
18    /// The angular velocity of the first link.
19    pub velocity_1: F32<B>,
20    /// The angular velocity of the second link.
21    pub velocity_2: F32<B>,
22}
23
24/// The parameters of Acrobot, in the order of gymnax's `EnvParams` leaves.
25/// Defaults follow `Acrobot-v1`.
26#[derive(Clone, Debug, Tree)]
27pub struct AcrobotParams<B: Backend> {
28    /// The time limit.
29    pub max_steps_in_episode: I32<B>,
30    /// The torque of each action (`[-1, 0, 1]`).
31    pub available_torque: Array<B, f32>,
32    /// The time step.
33    pub dt: F32<B>,
34    /// The length of the first link.
35    pub link_length_1: F32<B>,
36    /// The length of the second link.
37    pub link_length_2: F32<B>,
38    /// The mass of the first link.
39    pub link_mass_1: F32<B>,
40    /// The mass of the second link.
41    pub link_mass_2: F32<B>,
42    /// The position of the center of mass of the first link.
43    pub link_com_pos_1: F32<B>,
44    /// The position of the center of mass of the second link.
45    pub link_com_pos_2: F32<B>,
46    /// The moment of inertia of both links.
47    pub link_moi: F32<B>,
48    /// The largest angular velocity of the first link.
49    pub max_vel_1: F32<B>,
50    /// The largest angular velocity of the second link.
51    pub max_vel_2: F32<B>,
52    /// The bound of the uniform noise added to the torque.
53    pub torque_noise_max: F32<B>,
54}
55
56/// gymnax's Acrobot (`Acrobot-v1`): swing up a two-link pendulum by applying
57/// a torque of -1 (action 0), 0 (1), or +1 (2) at the joint between the links.
58///
59/// It reproduces gymnax 1.0 with the same operations (one step of the
60/// Runge-Kutta method, the same `wrap`, and the same noise draw), so the same
61/// keys and actions give the same trajectories. gymnax integrates the state
62/// augmented with the torque as an array of 5 elements; here each element is
63/// a scalar, with the same operations on each.
64#[derive(Clone, Copy, Debug, Default)]
65pub struct Acrobot;
66
67/// The state augmented with the torque: `[theta1, theta2, dtheta1, dtheta2,
68/// torque]`.
69type Augmented<B> = [F32<B>; 5];
70
71/// `pi` and `pi / 2` as gymnax's `float32` constants.
72const PI: f32 = std::f64::consts::PI as f32;
73const HALF_PI: f32 = (std::f64::consts::PI / 2.0) as f32;
74
75impl Acrobot {
76    fn observation<B: Backend>(&self, s: &AcrobotState<B>) -> Array<B, f32> {
77        jnp::stack(
78            &[
79                s.joint_angle1.cos(),
80                s.joint_angle1.sin(),
81                s.joint_angle2.cos(),
82                s.joint_angle2.sin(),
83                s.velocity_1,
84                s.velocity_2,
85            ],
86            0,
87        )
88    }
89
90    fn is_terminated<B: Backend>(&self, s: &AcrobotState<B>) -> Bool<B> {
91        (-s.joint_angle1.cos() - (s.joint_angle2 + s.joint_angle1).cos()).gt(1.0)
92    }
93
94    /// gymnax's `dsdt`: the time derivative of the augmented state.
95    fn dsdt<B: Backend>(&self, y: &Augmented<B>, p: &AcrobotParams<B>) -> Augmented<B> {
96        let (m1, m2) = (p.link_mass_1, p.link_mass_2);
97        let l1 = p.link_length_1;
98        let (lc1, lc2) = (p.link_com_pos_1, p.link_com_pos_2);
99        let (i1, i2) = (p.link_moi, p.link_moi);
100        let g = 9.8f32;
101        let [theta1, theta2, dtheta1, dtheta2, a] = *y;
102        let d1 = m1 * lc1.integer_pow(2)
103            + m2 * (l1.integer_pow(2) + lc2.integer_pow(2) + 2.0 * l1 * lc2 * theta2.cos())
104            + i1
105            + i2;
106        let d2 = m2 * (lc2.integer_pow(2) + l1 * lc2 * theta2.cos()) + i2;
107        let phi2 = m2 * lc2 * g * (theta1 + theta2 - HALF_PI).cos();
108        let phi1 = -m2 * l1 * lc2 * dtheta2.integer_pow(2) * theta2.sin()
109            - 2.0 * m2 * l1 * lc2 * dtheta2 * dtheta1 * theta2.sin()
110            + (m1 * lc1 + m2 * l1) * g * (theta1 - HALF_PI).cos()
111            + phi2;
112        let ddtheta2 =
113            (a + d2 / d1 * phi1 - m2 * l1 * lc2 * dtheta1.integer_pow(2) * theta2.sin() - phi2)
114                / (m2 * lc2.integer_pow(2) + i2 - d2.integer_pow(2) / d1);
115        let ddtheta1 = -(d2 * ddtheta2 + phi1) / d1;
116        [dtheta1, dtheta2, ddtheta1, ddtheta2, F32::new(0.0)]
117    }
118
119    /// gymnax's `rk4`: one step of the Runge-Kutta method.
120    fn rk4<B: Backend>(&self, y0: &Augmented<B>, p: &AcrobotParams<B>) -> Augmented<B> {
121        let axpy = |h: F32<B>, k: &Augmented<B>| -> Augmented<B> {
122            std::array::from_fn(|i| y0[i] + h * k[i])
123        };
124        let dt2 = p.dt / 2.0;
125        let k1 = self.dsdt(y0, p);
126        let k2 = self.dsdt(&axpy(dt2, &k1), p);
127        let k3 = self.dsdt(&axpy(dt2, &k2), p);
128        let k4 = self.dsdt(&axpy(p.dt, &k3), p);
129        let h = p.dt / 6.0;
130        std::array::from_fn(|i| y0[i] + h * (k1[i] + 2.0 * k2[i] + 2.0 * k3[i] + k4[i]))
131    }
132}
133
134/// gymnax's `wrap(x, m, big_m)` for `[-pi, pi)`, with the same operations.
135fn wrap<B: Backend>(x: F32<B>) -> F32<B> {
136    let (m, big_m) = (-PI, PI);
137    let diff = (std::f64::consts::PI - -std::f64::consts::PI) as f32;
138    let go_up = x.lt(m).cast::<f32>();
139    let go_down = x.ge(big_m).cast::<f32>();
140    let how_often = go_up * ((m - x) / diff).ceil() + go_down * ((x - big_m) / diff + 1.0).floor();
141    x - how_often * diff * go_down + how_often * diff * go_up
142}
143
144impl Environment for Acrobot {
145    type State<B: Backend> = AcrobotState<B>;
146    type Params<B: Backend> = AcrobotParams<B>;
147    type Obs<B: Backend> = Array<B, f32>;
148    type Action<B: Backend> = I32<B>;
149
150    fn name(&self) -> &str {
151        "Acrobot-v1"
152    }
153
154    fn action_space(&self) -> ActionSpace {
155        ActionSpace::Discrete(3)
156    }
157
158    fn default_params<B: Backend>(&self) -> AcrobotParams<B> {
159        AcrobotParams {
160            max_steps_in_episode: I32::new(500),
161            available_torque: Array::from_vec(vec![-1.0, 0.0, 1.0], [3]),
162            dt: F32::new(0.2),
163            link_length_1: F32::new(1.0),
164            link_length_2: F32::new(1.0),
165            link_mass_1: F32::new(1.0),
166            link_mass_2: F32::new(1.0),
167            link_com_pos_1: F32::new(0.5),
168            link_com_pos_2: F32::new(0.5),
169            link_moi: F32::new(1.0),
170            max_vel_1: F32::new((4.0 * std::f64::consts::PI) as f32),
171            max_vel_2: F32::new((9.0 * std::f64::consts::PI) as f32),
172            torque_noise_max: F32::new(0.0),
173        }
174    }
175
176    fn reset<B: Backend>(
177        &self,
178        key: Key<B>,
179        _params: &AcrobotParams<B>,
180    ) -> (Array<B, f32>, AcrobotState<B>) {
181        let init = random::uniform(&key, [4], -0.1f32, 0.1f32);
182        let part = |i: i64| init.get(i);
183        let state = AcrobotState {
184            time: I32::new(0),
185            joint_angle1: part(0),
186            joint_angle2: part(1),
187            velocity_1: part(2),
188            velocity_2: part(3),
189        };
190        (self.observation(&state), state)
191    }
192
193    fn step_env<B: Backend>(
194        &self,
195        key: Key<B>,
196        s: &AcrobotState<B>,
197        action: I32<B>,
198        p: &AcrobotParams<B>,
199    ) -> Transition<B, AcrobotState<B>, Array<B, f32>> {
200        let (lo, hi) = (-p.torque_noise_max, p.torque_noise_max);
201        // gymnax always draws the noise. When the range is empty (by
202        // default), `uniform` returns `max(lo, f * (hi - lo) + lo)` with
203        // `f * (hi - lo)` equal to `hi - lo` (a zero) whatever the random
204        // `f` in [0, 1) is, so natively the draw is skipped then.
205        let noise = if B::FAST_PATHS {
206            let range = hi - lo;
207            lax::select_with(
208                range.eq(0.0),
209                || lo.max(range + lo),
210                || random::uniform(&key, [], lo, hi).to_scalar(),
211            )
212        } else {
213            random::uniform(&key, [], lo, hi).to_scalar()
214        };
215        let torque = p.available_torque.get(action) + noise;
216        let y0 = [
217            s.joint_angle1,
218            s.joint_angle2,
219            s.velocity_1,
220            s.velocity_2,
221            torque,
222        ];
223        let ns = self.rk4(&y0, p);
224        let joint_angle1 = wrap(ns[0]);
225        let joint_angle2 = wrap(ns[1]);
226        let velocity_1 = ns[2].clamp(-p.max_vel_1, p.max_vel_1);
227        let velocity_2 = ns[3].clamp(-p.max_vel_2, p.max_vel_2);
228        let state = AcrobotState {
229            time: s.time + 1,
230            joint_angle1,
231            joint_angle2,
232            velocity_1,
233            velocity_2,
234        };
235        let terminated = self.is_terminated(&state);
236        // As in gymnax, `1 - done` is computed on integers.
237        let reward = -1.0 * (1 - terminated.cast::<i32>()).cast::<f32>();
238        Transition {
239            obs: self.observation(&state),
240            state,
241            reward,
242            terminated,
243        }
244    }
245
246    fn is_truncated<B: Backend>(&self, s: &AcrobotState<B>, p: &AcrobotParams<B>) -> Bool<B> {
247        s.time.ge(p.max_steps_in_episode)
248    }
249}