Skip to main content

ruxla_env/
jax_env.rs

1//! Environments written in JAX, imported from the directories that
2//! `python -m ruxla.export` writes.
3//!
4//! A directory has `manifest.json` (the name, the action space, and the
5//! number of leaves of an observation), `reset.json`, `step.json`, and
6//! optionally `legal_action_mask.json`: the functions of [`EnvFunctions`] as
7//! documents of `ruxla.export_jaxpr`, which [`ruxla_import`] reads.
8//! [`load_functions`] reads them, and [`crate::compiled::generate_from_functions`]
9//! compiles them ahead of time to Rust like the environments written with
10//! ruxla.
11
12use std::path::Path;
13
14use serde_json::Value;
15
16use crate::ActionSpace;
17use crate::compiled::EnvFunctions;
18
19/// The version of `manifest.json` that this crate reads.
20pub const MANIFEST_VERSION: u64 = 1;
21
22/// Errors while loading an imported environment.
23#[derive(Debug, thiserror::Error)]
24#[non_exhaustive]
25pub enum LoadError {
26    /// A file could not be read.
27    #[error("{path}: {source}")]
28    Io {
29        /// The file.
30        path: String,
31        /// The error.
32        source: std::io::Error,
33    },
34    /// A function could not be imported.
35    #[error("{path}: {source}")]
36    Import {
37        /// The file.
38        path: String,
39        /// The error.
40        source: ruxla_import::Error,
41    },
42    /// The manifest is not well formed.
43    #[error("{path}: malformed manifest: {message}")]
44    Manifest {
45        /// The file.
46        path: String,
47        /// What is wrong.
48        message: String,
49    },
50}
51
52fn read(path: &Path) -> Result<String, LoadError> {
53    std::fs::read_to_string(path).map_err(|source| LoadError::Io {
54        path: path.display().to_string(),
55        source,
56    })
57}
58
59fn import(path: &Path) -> Result<ruxla_ir::Function, LoadError> {
60    ruxla_import::from_json(&read(path)?).map_err(|source| LoadError::Import {
61        path: path.display().to_string(),
62        source,
63    })
64}
65
66/// Reads the functions of the imported environment in `dir`.
67///
68/// # Errors
69///
70/// Returns an error if a file is missing or malformed, or if a function
71/// uses a primitive or parameter that ruxla does not have.
72pub fn load_functions(dir: &Path) -> Result<EnvFunctions, LoadError> {
73    let manifest_path = dir.join("manifest.json");
74    let bad = |message: String| LoadError::Manifest {
75        path: manifest_path.display().to_string(),
76        message,
77    };
78    let manifest: Value =
79        serde_json::from_str(&read(&manifest_path)?).map_err(|e| bad(e.to_string()))?;
80    let version = manifest.get("manifest_version").and_then(Value::as_u64);
81    if version != Some(MANIFEST_VERSION) {
82        return Err(bad(format!(
83            "manifest version {version:?}; this build reads version {MANIFEST_VERSION}"
84        )));
85    }
86    let name = manifest
87        .get("name")
88        .and_then(Value::as_str)
89        .ok_or_else(|| bad(String::from("no name")))?
90        .to_string();
91    let num_obs = manifest
92        .get("num_obs")
93        .and_then(Value::as_u64)
94        .ok_or_else(|| bad(String::from("no num_obs")))? as usize;
95    let space = manifest
96        .get("action_space")
97        .ok_or_else(|| bad(String::from("no action_space")))?;
98    let action_space = action_space(space).map_err(bad)?;
99    let legal = dir.join("legal_action_mask.json");
100    Ok(EnvFunctions {
101        name,
102        action_space,
103        num_obs,
104        reset: import(&dir.join("reset.json"))?,
105        step: import(&dir.join("step.json"))?,
106        legal_action_mask: if legal.exists() {
107            Some(import(&legal)?)
108        } else {
109            None
110        },
111    })
112}
113
114/// An action space of a manifest: `{"kind": "discrete", "n": 9}`,
115/// `{"kind": "multi_discrete", "nvec": [5, 5]}`, or `{"kind": "box", "low":
116/// [...], "high": [...], "shape": [...]}`.
117pub(crate) fn action_space(v: &Value) -> Result<ActionSpace, String> {
118    let uints = |k: &str| -> Result<Vec<usize>, String> {
119        v.get(k)
120            .and_then(Value::as_array)
121            .ok_or_else(|| format!("action space without {k}"))?
122            .iter()
123            .map(|x| {
124                x.as_u64()
125                    .map(|x| x as usize)
126                    .ok_or_else(|| format!("{k}: {x}"))
127            })
128            .collect()
129    };
130    let floats = |k: &str| -> Result<Vec<f32>, String> {
131        v.get(k)
132            .and_then(Value::as_array)
133            .ok_or_else(|| format!("action space without {k}"))?
134            .iter()
135            .map(|x| {
136                x.as_f64()
137                    .map(|x| x as f32)
138                    .ok_or_else(|| format!("{k}: {x}"))
139            })
140            .collect()
141    };
142    match v.get("kind").and_then(Value::as_str) {
143        Some("discrete") => Ok(ActionSpace::Discrete(
144            v.get("n")
145                .and_then(Value::as_u64)
146                .ok_or("a discrete action space without n")? as usize,
147        )),
148        Some("multi_discrete") => Ok(ActionSpace::MultiDiscrete(uints("nvec")?)),
149        Some("box") => Ok(ActionSpace::Box {
150            low: floats("low")?,
151            high: floats("high")?,
152            shape: uints("shape")?,
153        }),
154        k => Err(format!("unknown kind of action space {k:?}")),
155    }
156}
157
158#[cfg(test)]
159mod tests {
160    use super::*;
161
162    #[test]
163    fn reads_action_spaces() {
164        let v: Value = serde_json::from_str(r#"{"kind": "discrete", "n": 3}"#).unwrap();
165        assert_eq!(action_space(&v).unwrap(), ActionSpace::Discrete(3));
166        let v: Value =
167            serde_json::from_str(r#"{"kind": "multi_discrete", "nvec": [2, 4]}"#).unwrap();
168        assert_eq!(
169            action_space(&v).unwrap(),
170            ActionSpace::MultiDiscrete(vec![2, 4])
171        );
172        let v: Value =
173            serde_json::from_str(r#"{"kind": "box", "low": [-1.0], "high": [2.5], "shape": [1]}"#)
174                .unwrap();
175        assert_eq!(
176            action_space(&v).unwrap(),
177            ActionSpace::Box {
178                low: vec![-1.0],
179                high: vec![2.5],
180                shape: vec![1]
181            }
182        );
183        let v: Value = serde_json::from_str(r#"{"kind": "graph"}"#).unwrap();
184        assert!(action_space(&v).is_err());
185    }
186}