Skip to main content

ruxla_env/
package.rs

1//! Writing environments as `.ruxlapkg` packages for the Python package.
2
3use crate::StepInput;
4use std::path::{Path, PathBuf};
5
6use ruxla_core::random::{self, Key};
7use ruxla_core::{Native, Trace, Tree, TreeDef, leaves, trace};
8use serde_json::{Map, Value, json};
9
10use crate::Environment;
11
12/// The version of the package layout written by [`export`].
13pub const SCHEMA_VERSION: u32 = 1;
14
15/// Errors from [`export`].
16#[derive(Debug, thiserror::Error)]
17#[non_exhaustive]
18pub enum ExportError {
19    /// Writing the package failed.
20    #[error("failed to write the package: {0}")]
21    Io(#[from] std::io::Error),
22}
23
24/// Describes a pytree structure as JSON for the Python package.
25fn structure(def: &TreeDef) -> Value {
26    let children = |c: &[TreeDef]| c.iter().map(structure).collect::<Vec<_>>();
27    match def {
28        TreeDef::Leaf => json!({"kind": "leaf"}),
29        TreeDef::None => json!({"kind": "none"}),
30        TreeDef::Tuple(c) => json!({"kind": "tuple", "children": children(c)}),
31        TreeDef::List(c) => json!({"kind": "list", "children": children(c)}),
32        TreeDef::Struct {
33            name,
34            fields,
35            children: c,
36        } => json!({"kind": "struct", "name": name, "fields": fields, "children": children(c)}),
37    }
38}
39
40/// Writes a `.ruxlapkg` package of any functions: each is traced and
41/// written as IR, and [`finish`](Self::finish) writes the manifest. The
42/// Python package `ruxla` loads it with `ruxla.load` and calls the functions
43/// inside JAX programs through the primitive `ruxla_call`. [`export`] uses
44/// it for environments.
45///
46/// # Examples
47///
48/// ```no_run
49/// use ruxla_core::{Array, Native, Trace, jnp};
50///
51/// let mut package = ruxla_env::PackageWriter::new("sin.ruxlapkg")?;
52/// package.function(
53///     "sin",
54///     |x: Array<Trace, f32>| jnp::sin(&x),
55///     &Array::<Native, f32>::from_vec(vec![0.0; 3], [3]),
56/// )?;
57/// package.finish("functions", serde_json::Map::new())?;
58/// # Ok::<(), ruxla_env::ExportError>(())
59/// ```
60#[derive(Debug)]
61pub struct PackageWriter {
62    dir: PathBuf,
63    functions: Map<String, Value>,
64}
65
66impl PackageWriter {
67    /// Starts a package in the directory `path`, which is created if needed.
68    ///
69    /// # Errors
70    ///
71    /// Returns an error if the directory cannot be created.
72    pub fn new(path: impl AsRef<Path>) -> Result<Self, ExportError> {
73        let dir = path.as_ref().to_path_buf();
74        std::fs::create_dir_all(&dir)?;
75        Ok(Self {
76            dir,
77            functions: Map::new(),
78        })
79    }
80
81    /// Traces `f` on values shaped like `example` (with `B = Trace`) and
82    /// writes it as `name`, with the pytree structure of its inputs and
83    /// outputs.
84    ///
85    /// # Errors
86    ///
87    /// Returns an error if the file cannot be written.
88    pub fn function<I: Tree<Native>, O: Tree<Trace>>(
89        &mut self,
90        name: &str,
91        f: impl FnOnce(I::On<Trace>) -> O,
92        example: &I,
93    ) -> Result<(), ExportError> {
94        let traced = trace(f, example);
95        let file = format!("{name}.ruxlair");
96        std::fs::write(
97            self.dir.join(&file),
98            ruxla_ir::serialize::to_bytes(&traced.function),
99        )?;
100        self.functions.insert(
101            name.to_owned(),
102            json!({
103                "file": file,
104                "inputs": structure(&traced.in_def),
105                "outputs": structure(&traced.out_def),
106            }),
107        );
108        Ok(())
109    }
110
111    /// Writes the manifest, with the package's `kind` (such as `"env"`) and
112    /// `extra` fields (such as `"env"`, the description of an environment).
113    ///
114    /// # Errors
115    ///
116    /// Returns an error if the manifest cannot be written.
117    pub fn finish(self, kind: &str, extra: Map<String, Value>) -> Result<(), ExportError> {
118        let mut manifest = Map::new();
119        manifest.insert("schema_version".into(), json!(SCHEMA_VERSION));
120        manifest.insert("kind".into(), json!(kind));
121        manifest.insert("ruxla_version".into(), json!(env!("CARGO_PKG_VERSION")));
122        manifest.insert("functions".into(), Value::Object(self.functions));
123        manifest.extend(extra);
124        std::fs::write(
125            self.dir.join("manifest.json"),
126            serde_json::to_string_pretty(&Value::Object(manifest)).expect("JSON") + "\n",
127        )?;
128        Ok(())
129    }
130}
131
132/// Writes an environment as a `.ruxlapkg` package (a directory) for the
133/// Python package `ruxla`, which loads it with `ruxla.load_env`.
134///
135/// The package holds `reset`, `step` (with automatic reset; it returns
136/// `(obs, state, reward, terminated, truncated, final_observation,
137/// discount)`), and `default_params`, traced for single episodes with
138/// `B = Trace` from examples made natively (the default parameters and a
139/// reset state). JAX's `vmap` batches them through ruxla's `vmap`.
140///
141/// # Errors
142///
143/// Returns an error if the files cannot be written.
144pub fn export<E: Environment>(env: &E, path: impl AsRef<Path>) -> Result<(), ExportError> {
145    let mut package = PackageWriter::new(path)?;
146    let params = env.default_params::<Native>();
147    let key = random::key::<Native>(0);
148    let (obs, state) = env.reset(key.clone(), &params);
149
150    package.function(
151        "reset",
152        |(k, p): (Key<Trace>, E::Params<Trace>)| env.reset(k, &p),
153        &(key.clone(), params.clone()),
154    )?;
155    package.function(
156        "step",
157        |(k, s, a, p): StepInput<Trace, E>| {
158            let st = env.step(k, &s, a, &p);
159            (
160                st.obs,
161                st.state,
162                st.reward,
163                st.terminated,
164                st.truncated,
165                st.final_observation,
166                st.discount,
167            )
168        },
169        &(
170            key,
171            state.clone(),
172            <E::Action<Native> as crate::ActionValue<Native>>::pattern(&env.action_space(), 0),
173            params,
174        ),
175    )?;
176    package.function(
177        "default_params",
178        |(): ()| env.default_params::<Trace>(),
179        &(),
180    )?;
181    // The legal action mask of a state, for environments that have one (Pgx).
182    if env.legal_action_mask(&state).is_some() {
183        package.function(
184            "legal_action_mask",
185            |s: E::State<Trace>| env.legal_action_mask(&s).expect("a legal action mask"),
186            &state,
187        )?;
188    }
189
190    let obs_shapes: Vec<Vec<usize>> = leaves(&obs).iter().map(|l| l.shape().to_vec()).collect();
191    let obs_shape = match obs_shapes.as_slice() {
192        [one] => json!(one),
193        _ => json!(obs_shapes),
194    };
195    let mut extra = Map::new();
196    extra.insert(
197        "env".into(),
198        json!({
199            "name": env.name(),
200            "num_actions": env.num_actions(),
201            "action_space": match env.action_space() {
202                crate::ActionSpace::Discrete(n) => json!({"type": "discrete", "n": n}),
203                crate::ActionSpace::MultiDiscrete(nvec) => {
204                    json!({"type": "multi_discrete", "nvec": nvec})
205                }
206                crate::ActionSpace::Box { low, high, shape } => {
207                    json!({"type": "box", "low": low, "high": high, "shape": shape})
208                }
209            },
210            "obs_shape": obs_shape,
211        }),
212    );
213    package.finish("env", extra)
214}