1use ruxla_core::random::{self, Key};
4use ruxla_core::{Array, Backend, Bool, F32, I32, Tree, jnp, lax};
5
6use crate::{ActionSpace, Environment, Transition};
7
8#[derive(Clone, Debug, Tree)]
11pub struct AcrobotState<B: Backend> {
12 pub time: I32<B>,
14 pub joint_angle1: F32<B>,
16 pub joint_angle2: F32<B>,
18 pub velocity_1: F32<B>,
20 pub velocity_2: F32<B>,
22}
23
24#[derive(Clone, Debug, Tree)]
27pub struct AcrobotParams<B: Backend> {
28 pub max_steps_in_episode: I32<B>,
30 pub available_torque: Array<B, f32>,
32 pub dt: F32<B>,
34 pub link_length_1: F32<B>,
36 pub link_length_2: F32<B>,
38 pub link_mass_1: F32<B>,
40 pub link_mass_2: F32<B>,
42 pub link_com_pos_1: F32<B>,
44 pub link_com_pos_2: F32<B>,
46 pub link_moi: F32<B>,
48 pub max_vel_1: F32<B>,
50 pub max_vel_2: F32<B>,
52 pub torque_noise_max: F32<B>,
54}
55
56#[derive(Clone, Copy, Debug, Default)]
65pub struct Acrobot;
66
67type Augmented<B> = [F32<B>; 5];
70
71const 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 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 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
134fn 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 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 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}