1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
use super::{BuildEnv, BuildEnvError, EnvStructure, Environment, Successor};
use crate::feedback::Reward;
use crate::logging::StatsLogger;
use crate::spaces::{Indexed, IndexedTypeSpace, IntervalSpace};
use crate::Prng;
use rand::distributions::{Distribution, Uniform};
use serde::{Deserialize, Serialize};
#[derive(Debug, Default, Copy, Clone, PartialEq, Serialize, Deserialize)]
pub struct CartPoleConfig {
pub physics_config: PhysicalConstants,
pub env_config: EnvironmentParams,
}
impl BuildEnv for CartPoleConfig {
type Observation = CartPolePhysicalState;
type Action = Push;
type Feedback = Reward;
type ObservationSpace = CartPolePhysicalStateSpace;
type ActionSpace = IndexedTypeSpace<Push>;
type FeedbackSpace = IntervalSpace<Reward>;
type Environment = CartPole;
fn build_env(&self, _: &mut Prng) -> Result<Self::Environment, BuildEnvError> {
Ok(CartPole::new(self.physics_config, self.env_config))
}
}
#[derive(Debug, Default, Copy, Clone, PartialEq, Serialize, Deserialize)]
pub struct CartPole {
phys: InternalPhysicalConstants,
env: EnvironmentParams,
}
impl CartPole {
#[must_use]
pub fn new(phys: PhysicalConstants, env: EnvironmentParams) -> Self {
Self {
phys: phys.into(),
env,
}
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Indexed, Serialize, Deserialize)]
pub enum Push {
Left,
Right,
}
impl EnvStructure for CartPole {
type ObservationSpace = CartPolePhysicalStateSpace;
type ActionSpace = IndexedTypeSpace<Push>;
type FeedbackSpace = IntervalSpace<Reward>;
fn observation_space(&self) -> Self::ObservationSpace {
let max_pos = self.env.max_pos;
let max_angle = self.env.max_angle;
CartPolePhysicalStateSpace {
cart_position: IntervalSpace::new(-max_pos, max_pos),
cart_velocity: IntervalSpace::default(),
pole_angle: IntervalSpace::new(-max_angle, max_angle),
pole_angular_velocity: IntervalSpace::default(),
}
}
fn action_space(&self) -> Self::ActionSpace {
IndexedTypeSpace::new()
}
fn feedback_space(&self) -> Self::FeedbackSpace {
IntervalSpace::new(Reward(0.0), Reward(1.0))
}
fn discount_factor(&self) -> f64 {
self.env.discount_factor
}
}
impl Environment for CartPole {
type State = CartPoleInternalState;
type Observation = CartPolePhysicalState;
type Action = Push;
type Feedback = Reward;
fn initial_state(&self, rng: &mut Prng) -> Self::State {
let dist = Uniform::new_inclusive(-0.05, 0.05);
CartPoleInternalState {
physical: CartPolePhysicalState {
cart_position: dist.sample(rng),
cart_velocity: dist.sample(rng),
pole_angle: dist.sample(rng),
pole_angular_velocity: dist.sample(rng),
},
cached_normal_velocity_is_positive: true,
}
}
fn observe(&self, state: &Self::State, _: &mut Prng) -> Self::Observation {
assert!(
state.physical.cart_position >= -self.env.max_pos
&& state.physical.cart_position <= self.env.max_pos
&& state.physical.pole_angle >= -self.env.max_angle
&& state.physical.pole_angle <= self.env.max_angle,
"out-of-bounds state should not have been produced"
);
state.physical
}
fn step(
&self,
state: Self::State,
action: &Self::Action,
_: &mut Prng,
_: &mut dyn StatsLogger,
) -> (Successor<Self::State>, Self::Feedback) {
let applied_force = match action {
Push::Left => -self.env.action_force,
Push::Right => self.env.action_force,
};
let next_state = self.phys.next_state(&state, applied_force);
let reward = 1.0;
let terminal = next_state.physical.cart_position.abs() > self.env.max_pos
|| next_state.physical.pole_angle.abs() > self.env.max_angle;
let successor = if terminal {
Successor::Terminate
} else {
Successor::Continue(next_state)
};
(successor, reward.into())
}
}
#[derive(Debug, Copy, Clone, PartialEq, Serialize, Deserialize)]
pub struct PhysicalConstants {
pub gravity: f64,
pub mass_cart: f64,
pub mass_pole: f64,
pub length_half_pole: f64,
pub friction_cart: f64,
pub friction_pole: f64,
pub time_step: f64,
}
impl Default for PhysicalConstants {
fn default() -> Self {
Self {
gravity: 9.8,
mass_cart: 1.0,
mass_pole: 0.1,
length_half_pole: 0.5,
friction_cart: 0.01,
friction_pole: 0.01,
time_step: 0.02,
}
}
}
#[derive(Debug, Copy, Clone, PartialEq, Serialize, Deserialize)]
pub struct EnvironmentParams {
pub action_force: f64,
pub max_pos: f64,
pub max_angle: f64,
pub discount_factor: f64,
}
impl Default for EnvironmentParams {
fn default() -> Self {
Self {
action_force: 10.0,
max_pos: 2.4,
max_angle: 12.0f64.to_radians(),
discount_factor: 0.99,
}
}
}
#[derive(Debug, Copy, Clone, PartialEq, Serialize, Deserialize)]
#[serde(into = "PhysicalConstants", from = "PhysicalConstants")]
struct InternalPhysicalConstants {
c: PhysicalConstants,
total_weight: f64,
inv_total_mass: f64,
mass_length_pole: f64,
}
impl Default for InternalPhysicalConstants {
fn default() -> Self {
PhysicalConstants::default().into()
}
}
impl From<PhysicalConstants> for InternalPhysicalConstants {
fn from(c: PhysicalConstants) -> Self {
let total_mass = c.mass_cart + c.mass_pole;
let total_weight = c.gravity * total_mass;
let inv_total_mass = total_mass.recip();
let mass_length_pole = c.mass_pole * c.length_half_pole;
Self {
c,
total_weight,
inv_total_mass,
mass_length_pole,
}
}
}
impl From<InternalPhysicalConstants> for PhysicalConstants {
fn from(ic: InternalPhysicalConstants) -> Self {
ic.c
}
}
#[derive(Debug, Copy, Clone, PartialEq, Serialize, Deserialize)]
pub struct CartPolePhysicalState {
pub cart_position: f64,
pub cart_velocity: f64,
pub pole_angle: f64,
pub pole_angular_velocity: f64,
}
#[derive(Debug, Copy, Clone, PartialEq, ProductSpace, Serialize, Deserialize)]
#[element(CartPolePhysicalState)]
pub struct CartPolePhysicalStateSpace {
pub cart_position: IntervalSpace<f64>,
pub cart_velocity: IntervalSpace<f64>,
pub pole_angle: IntervalSpace<f64>,
pub pole_angular_velocity: IntervalSpace<f64>,
}
#[derive(Debug, Copy, Clone, PartialEq, Serialize, Deserialize)]
pub struct CartPoleInternalState {
physical: CartPolePhysicalState,
cached_normal_velocity_is_positive: bool,
}
impl InternalPhysicalConstants {
pub fn next_state(
&self,
state: &CartPoleInternalState,
applied_force: f64,
) -> CartPoleInternalState {
let phys = &state.physical;
let mut signed_cart_friction = if state.cached_normal_velocity_is_positive {
self.c.friction_cart
} else {
-self.c.friction_cart
};
let (sin_angle, cos_angle) = phys.pole_angle.sin_cos();
let angular_velocity_squared = phys.pole_angular_velocity * phys.pole_angular_velocity;
let mut angular_acceleration = self.angular_acceleration(
phys,
applied_force,
signed_cart_friction,
angular_velocity_squared,
sin_angle,
cos_angle,
);
let mut normal_force = self.normal_force(
angular_acceleration,
angular_velocity_squared,
sin_angle,
cos_angle,
);
let normal_velocity_is_positive = (normal_force * phys.cart_velocity).is_sign_positive();
if normal_velocity_is_positive != state.cached_normal_velocity_is_positive {
signed_cart_friction = -signed_cart_friction;
angular_acceleration = self.angular_acceleration(
phys,
applied_force,
signed_cart_friction,
angular_velocity_squared,
sin_angle,
cos_angle,
);
normal_force = self.normal_force(
angular_acceleration,
angular_velocity_squared,
sin_angle,
cos_angle,
);
}
let force_pole = self.mass_length_pole
* (angular_velocity_squared * sin_angle + angular_acceleration * cos_angle);
let force_friction = -signed_cart_friction * normal_force;
let net_force = applied_force + force_pole + force_friction;
let cart_acceleration = net_force * self.inv_total_mass;
let cart_velocity = phys.cart_velocity + self.c.time_step * cart_acceleration;
let cart_position = phys.cart_position + self.c.time_step * cart_velocity;
let pole_angular_velocity =
phys.pole_angular_velocity + self.c.time_step * angular_acceleration;
let pole_angle = phys.pole_angle + self.c.time_step * phys.pole_angular_velocity;
CartPoleInternalState {
physical: CartPolePhysicalState {
cart_position,
cart_velocity,
pole_angle,
pole_angular_velocity,
},
cached_normal_velocity_is_positive: normal_velocity_is_positive,
}
}
fn angular_acceleration(
&self,
state: &CartPolePhysicalState,
applied_force: f64,
signed_cart_friction: f64,
angular_velocity_squared: f64,
sin_angle: f64,
cos_angle: f64,
) -> f64 {
let alpha = (-applied_force
- self.mass_length_pole
* angular_velocity_squared
* (sin_angle + signed_cart_friction * cos_angle))
* self.inv_total_mass;
let beta = self.c.friction_pole * state.pole_angular_velocity / self.mass_length_pole;
let numerator = self.c.gravity * sin_angle
+ cos_angle * (alpha + self.c.gravity * signed_cart_friction)
- beta;
let denominator = self.c.length_half_pole
* (4.0 / 3.0
- self.c.mass_pole
* cos_angle
* self.inv_total_mass
* (cos_angle - signed_cart_friction));
numerator / denominator
}
fn normal_force(
&self,
angular_acceleration: f64,
angular_velocity_squared: f64,
sin_angle: f64,
cos_angle: f64,
) -> f64 {
self.total_weight
- self.mass_length_pole
* (angular_acceleration * sin_angle + angular_velocity_squared * cos_angle)
}
}
#[cfg(test)]
mod tests {
use super::super::testing;
use super::*;
#[test]
fn run_default() {
testing::check_structured_env(&CartPole::default(), 1000, 0);
}
}