1use 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
12pub const SCHEMA_VERSION: u32 = 1;
14
15#[derive(Debug, thiserror::Error)]
17#[non_exhaustive]
18pub enum ExportError {
19 #[error("failed to write the package: {0}")]
21 Io(#[from] std::io::Error),
22}
23
24fn 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#[derive(Debug)]
61pub struct PackageWriter {
62 dir: PathBuf,
63 functions: Map<String, Value>,
64}
65
66impl PackageWriter {
67 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 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 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
132pub 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(), ¶ms);
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 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}