Skip to main content

ruxla_env/
action.rs

1//! Actions: discrete ([`I32`]), several discrete components
2//! (`Array<B, i32>`), or continuous (`Array<B, f32>` in a box), and their
3//! spaces (gymnax's `action_space`); and the choice of a legal action from a
4//! mask, for tests and benchmarks.
5
6use ruxla_core::{Array, Backend, I32};
7
8/// The most joint actions that a legal action mask covers (see
9/// [`ActionSpace::mask_len`]).
10pub const MAX_MASK_ACTIONS: usize = 1 << 20;
11
12/// The actions of an environment (gymnax's `action_space`).
13#[derive(Clone, Debug, PartialEq)]
14pub enum ActionSpace {
15    /// Integers `0..n` (`I32`).
16    Discrete(usize),
17    /// Arrays of `i32` of shape `[nvec.len()]`, component `k` in
18    /// `0..nvec[k]` (Jumanji's `MultiDiscreteArray`).
19    MultiDiscrete(Vec<usize>),
20    /// Arrays of `f32` of `shape`, each element between `low` and `high`
21    /// (one bound per element, in row-major order).
22    Box {
23        /// The lower bounds.
24        low: Vec<f32>,
25        /// The upper bounds.
26        high: Vec<f32>,
27        /// The shape of an action.
28        shape: Vec<usize>,
29    },
30}
31
32impl ActionSpace {
33    /// A box with the same bounds for every element.
34    pub fn uniform_box(low: f32, high: f32, shape: &[usize]) -> Self {
35        let n = shape.iter().product();
36        ActionSpace::Box {
37            low: vec![low; n],
38            high: vec![high; n],
39            shape: shape.to_vec(),
40        }
41    }
42
43    /// The number of discrete actions (0 for a box).
44    pub fn num_actions(&self) -> usize {
45        match self {
46            ActionSpace::Discrete(n) => *n,
47            ActionSpace::MultiDiscrete(_) | ActionSpace::Box { .. } => 0,
48        }
49    }
50
51    /// The number of joint discrete actions (the size of a legal action
52    /// mask): `n`, or the product of `nvec`; 0 for a box.
53    pub fn num_joint_actions(&self) -> usize {
54        match self {
55            ActionSpace::Discrete(n) => *n,
56            ActionSpace::MultiDiscrete(nvec) => nvec.iter().product(),
57            ActionSpace::Box { .. } => 0,
58        }
59    }
60
61    /// The size of a legal action mask: the number of joint actions, or 0
62    /// when there are more than [`MAX_MASK_ACTIONS`] (an environment with
63    /// that many joint actions, such as Jumanji's JobShop with 21^10, has no
64    /// mask: [`crate::Environment::legal_action_mask`] gives `None`).
65    ///
66    /// # Examples
67    ///
68    /// ```
69    /// use ruxla_env::ActionSpace;
70    ///
71    /// assert_eq!(ActionSpace::MultiDiscrete(vec![40, 20]).mask_len(), 800);
72    /// assert_eq!(ActionSpace::MultiDiscrete(vec![21; 10]).mask_len(), 0);
73    /// ```
74    pub fn mask_len(&self) -> usize {
75        let n = match self {
76            ActionSpace::Discrete(n) => Some(*n),
77            ActionSpace::MultiDiscrete(nvec) => {
78                nvec.iter().try_fold(1usize, |a, &n| a.checked_mul(n))
79            }
80            ActionSpace::Box { .. } => Some(0),
81        };
82        n.filter(|&n| n <= MAX_MASK_ACTIONS).unwrap_or(0)
83    }
84
85    /// The number of elements of an action in a flat buffer (1 for a
86    /// discrete action).
87    pub fn flat_len(&self) -> usize {
88        match self {
89            ActionSpace::Discrete(_) => 1,
90            ActionSpace::MultiDiscrete(nvec) => nvec.len(),
91            ActionSpace::Box { shape, .. } => shape.iter().product(),
92        }
93    }
94}
95
96/// The actions of a batch of environments in a flat buffer: one integer
97/// per environment, or [`ActionSpace::flat_len`] floats per environment.
98#[derive(Clone, Copy, Debug)]
99pub enum Actions<'a> {
100    /// Discrete actions.
101    Discrete(&'a [i32]),
102    /// Actions of several discrete components, `dim` each.
103    MultiDiscrete {
104        /// The components, environment after environment.
105        data: &'a [i32],
106        /// The components of one action.
107        dim: usize,
108    },
109    /// Continuous actions, `dim` elements each.
110    Continuous {
111        /// The elements, environment after environment.
112        data: &'a [f32],
113        /// The elements of one action.
114        dim: usize,
115    },
116}
117
118impl Actions<'_> {
119    /// The number of actions.
120    pub fn len(&self) -> usize {
121        match self {
122            Actions::Discrete(a) => a.len(),
123            Actions::MultiDiscrete { data, dim } => data.len() / (*dim).max(1),
124            Actions::Continuous { data, dim } => data.len() / (*dim).max(1),
125        }
126    }
127
128    /// Whether there are no actions.
129    pub fn is_empty(&self) -> bool {
130        self.len() == 0
131    }
132}
133
134/// A type of actions ([`crate::Environment::Action`]).
135pub trait ActionValue<B: Backend>: Sized {
136    /// Action `i` of a fixed pseudo-random sequence in `space`, for tests
137    /// and benchmarks.
138    fn pattern(space: &ActionSpace, i: u64) -> Self;
139
140    /// The action of environment `i` in a flat buffer.
141    ///
142    /// # Panics
143    ///
144    /// Panics if the buffer has the other kind of actions.
145    fn from_flat(actions: Actions<'_>, i: usize) -> Self;
146
147    /// The joint action `index` (see [`choose_legal`]): the index itself,
148    /// or its components in row-major order of `nvec`.
149    ///
150    /// # Panics
151    ///
152    /// Panics for continuous actions.
153    fn from_joint(space: &ActionSpace, index: usize) -> Self;
154}
155
156/// The joint action that tests and benchmarks take where the environment
157/// gives a legal action mask (row-major over the joint actions): the
158/// [`pattern_discrete`]`(i, count)`-th legal one (0 if none is legal), the
159/// same in every implementation.
160pub fn choose_legal(mask: &[bool], i: u64) -> usize {
161    let count = mask.iter().filter(|&&m| m).count();
162    if count == 0 {
163        return 0;
164    }
165    let k = pattern_discrete(i, count) as usize;
166    mask.iter()
167        .enumerate()
168        .filter(|(_, m)| **m)
169        .nth(k)
170        .map_or(0, |(j, _)| j)
171}
172
173/// The components of joint action `index` over `nvec` (row-major).
174pub fn unravel_joint(index: usize, nvec: &[usize], out: &mut [i32]) {
175    let mut rest = index;
176    for k in (0..nvec.len()).rev() {
177        out[k] = (rest % nvec[k].max(1)) as i32;
178        rest /= nvec[k].max(1);
179    }
180}
181
182/// The `i`th of the pseudo-random sequence of discrete actions in `0..n`.
183pub fn pattern_discrete(i: u64, n: usize) -> i32 {
184    (i.wrapping_mul(2_654_435_761) % n.max(1) as u64) as i32
185}
186
187/// Element `k` of the `i`th of the pseudo-random sequence of continuous
188/// actions between `low` and `high`.
189pub fn pattern_continuous(i: u64, k: usize, low: f32, high: f32) -> f32 {
190    let h = i
191        .wrapping_mul(2_654_435_761)
192        .wrapping_add(k as u64 * 40_503)
193        % 1001;
194    low + (high - low) * (h as f32 / 1000.0)
195}
196
197impl<B: Backend> ActionValue<B> for I32<B> {
198    fn pattern(space: &ActionSpace, i: u64) -> Self {
199        I32::new(pattern_discrete(i, space.num_actions()))
200    }
201
202    #[inline]
203    fn from_flat(actions: Actions<'_>, i: usize) -> Self {
204        match actions {
205            Actions::Discrete(a) => I32::new(a[i]),
206            _ => panic!("discrete actions expected"),
207        }
208    }
209
210    fn from_joint(_: &ActionSpace, index: usize) -> Self {
211        I32::new(index as i32)
212    }
213}
214
215impl<B: Backend> ActionValue<B> for Array<B, i32> {
216    fn pattern(space: &ActionSpace, i: u64) -> Self {
217        let ActionSpace::MultiDiscrete(nvec) = space else {
218            panic!("multi-discrete actions expected");
219        };
220        let v: Vec<i32> = nvec
221            .iter()
222            .enumerate()
223            .map(|(k, &n)| pattern_discrete(i.wrapping_add(k as u64 * 40_503), n))
224            .collect();
225        Array::from_vec(v, [nvec.len()])
226    }
227
228    #[inline]
229    fn from_flat(actions: Actions<'_>, i: usize) -> Self {
230        match actions {
231            Actions::MultiDiscrete { data, dim } => {
232                Array::from_slice(&data[i * dim..(i + 1) * dim], [dim])
233            }
234            _ => panic!("multi-discrete actions expected"),
235        }
236    }
237
238    fn from_joint(space: &ActionSpace, index: usize) -> Self {
239        let ActionSpace::MultiDiscrete(nvec) = space else {
240            panic!("multi-discrete actions expected");
241        };
242        let mut v = vec![0i32; nvec.len()];
243        unravel_joint(index, nvec, &mut v);
244        Array::from_vec(v, [nvec.len()])
245    }
246}
247
248impl<B: Backend> ActionValue<B> for Array<B, f32> {
249    fn pattern(space: &ActionSpace, i: u64) -> Self {
250        let ActionSpace::Box { low, high, shape } = space else {
251            panic!("a box of actions expected");
252        };
253        let n = low.len();
254        let element = |k: usize| pattern_continuous(i, k, low[k], high[k]);
255        if n <= 8 {
256            // `from_slice` copies a small array without allocating, so that
257            // benchmarks do not time an allocation for every action.
258            let mut v = [0.0; 8];
259            for (k, e) in v.iter_mut().take(n).enumerate() {
260                *e = element(k);
261            }
262            Array::from_slice(&v[..n], shape.as_slice())
263        } else {
264            Array::from_vec((0..n).map(element).collect(), shape.as_slice())
265        }
266    }
267
268    #[inline]
269    fn from_flat(actions: Actions<'_>, i: usize) -> Self {
270        match actions {
271            Actions::Continuous { data, dim } => {
272                Array::from_slice(&data[i * dim..(i + 1) * dim], [dim])
273            }
274            _ => panic!("continuous actions expected"),
275        }
276    }
277
278    fn from_joint(_: &ActionSpace, _: usize) -> Self {
279        panic!("continuous actions have no joint index")
280    }
281}