1use ruxla_core::{Array, Backend, I32};
7
8pub const MAX_MASK_ACTIONS: usize = 1 << 20;
11
12#[derive(Clone, Debug, PartialEq)]
14pub enum ActionSpace {
15 Discrete(usize),
17 MultiDiscrete(Vec<usize>),
20 Box {
23 low: Vec<f32>,
25 high: Vec<f32>,
27 shape: Vec<usize>,
29 },
30}
31
32impl ActionSpace {
33 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 pub fn num_actions(&self) -> usize {
45 match self {
46 ActionSpace::Discrete(n) => *n,
47 ActionSpace::MultiDiscrete(_) | ActionSpace::Box { .. } => 0,
48 }
49 }
50
51 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 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 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#[derive(Clone, Copy, Debug)]
99pub enum Actions<'a> {
100 Discrete(&'a [i32]),
102 MultiDiscrete {
104 data: &'a [i32],
106 dim: usize,
108 },
109 Continuous {
111 data: &'a [f32],
113 dim: usize,
115 },
116}
117
118impl Actions<'_> {
119 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 pub fn is_empty(&self) -> bool {
130 self.len() == 0
131 }
132}
133
134pub trait ActionValue<B: Backend>: Sized {
136 fn pattern(space: &ActionSpace, i: u64) -> Self;
139
140 fn from_flat(actions: Actions<'_>, i: usize) -> Self;
146
147 fn from_joint(space: &ActionSpace, index: usize) -> Self;
154}
155
156pub 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
173pub 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
182pub 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
187pub 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 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}