1use serde::{Deserialize, Serialize};
2
3use crate::action::Action;
4use crate::condition::Condition;
5use crate::graph::Graph;
6use crate::policy::{DiffPolicy, MatchPolicy};
7
8#[derive(Debug, Clone, Serialize, Deserialize)]
10pub struct TraceEntry {
11 pub t: u64,
13 pub action: String,
15 pub res: f64,
17 pub energy: f64,
19 pub graph_size: usize,
21 pub condition: String,
23}
24
25#[derive(Debug, Clone, Serialize, Deserialize)]
39pub struct Trace {
40 pub config_n_modes: usize,
41 pub config_latent_dim: usize,
42 pub config_eps: f64,
43 pub config_seed: Option<u64>,
45 pub config_schedule: String,
47 pub config_condition: Condition,
49 pub config_match_policy: MatchPolicy,
51 pub config_diff_policy: DiffPolicy,
53 pub config_stutter_k: u64,
55 pub config_optical: Option<String>,
58 pub config_merge_tau: f64,
61 #[serde(default, skip_serializing_if = "Option::is_none")]
67 pub initial_graph: Option<Graph>,
68 pub entries: Vec<TraceEntry>,
69}
70
71impl Trace {
72 #[allow(clippy::too_many_arguments)]
73 pub fn new(
74 n_modes: usize,
75 latent_dim: usize,
76 eps: f64,
77 seed: Option<u64>,
78 schedule: &str,
79 condition: Condition,
80 match_policy: MatchPolicy,
81 diff_policy: DiffPolicy,
82 stutter_k: u64,
83 optical: Option<String>,
84 merge_tau: f64,
85 initial_graph: Option<Graph>,
86 ) -> Self {
87 Trace {
88 config_n_modes: n_modes,
89 config_latent_dim: latent_dim,
90 config_eps: eps,
91 config_seed: seed,
92 config_schedule: schedule.to_string(),
93 config_condition: condition,
94 config_match_policy: match_policy,
95 config_diff_policy: diff_policy,
96 config_stutter_k: stutter_k,
97 config_optical: optical,
98 config_merge_tau: merge_tau,
99 initial_graph,
100 entries: Vec::new(),
101 }
102 }
103
104 pub fn push(
105 &mut self,
106 t: u64,
107 action: Action,
108 residual: f64,
109 energy: f64,
110 graph_size: usize,
111 condition: &str,
112 ) {
113 self.entries.push(TraceEntry {
114 t,
115 action: action.symbol().to_string(),
116 res: residual,
117 energy,
118 graph_size,
119 condition: condition.to_string(),
120 });
121 }
122
123 pub fn to_jsonl(&self) -> String {
125 let mut out = String::new();
126 let mut header = serde_json::json!({
130 "type": "config",
131 "n_modes": self.config_n_modes,
132 "latent_dim": self.config_latent_dim,
133 "eps": self.config_eps,
134 "seed": self.config_seed,
135 "schedule": self.config_schedule,
136 "condition": self.config_condition,
137 "match_policy": self.config_match_policy,
138 "diff_policy": self.config_diff_policy,
139 "stutter_k": self.config_stutter_k,
140 "optical": self.config_optical,
141 "merge_tau": self.config_merge_tau,
142 });
143 if let Some(ref g0) = self.initial_graph {
144 header["initial_graph"] = serde_json::json!(g0);
145 }
146 out.push_str(&serde_json::to_string(&header).unwrap());
147 out.push('\n');
148 for entry in &self.entries {
149 out.push_str(&serde_json::to_string(entry).unwrap());
150 out.push('\n');
151 }
152 out
153 }
154
155 pub fn action_sequence(&self) -> String {
157 self.entries
158 .iter()
159 .map(|e| e.action.as_str())
160 .collect::<Vec<_>>()
161 .join("")
162 }
163}
164
165pub fn initial_graph_of(g0: &Graph) -> Option<Graph> {
176 if g0.size() == 0 {
177 None
178 } else {
179 Some(g0.clone())
180 }
181}
182
183#[cfg(test)]
184mod tests {
185 use super::*;
186
187 #[test]
192 fn header_round_trips_seed_schedule_condition_match_policy() {
193 let trace = Trace::new(
194 256,
195 64,
196 1.0,
197 Some(7),
198 "opdms",
199 Condition::WorldModel,
200 MatchPolicy::Merge,
201 DiffPolicy::GraphConditioned,
202 3,
203 Some("fft".to_string()),
204 0.7,
205 None,
206 );
207 let jsonl = trace.to_jsonl();
208 let header: serde_json::Value =
209 serde_json::from_str(jsonl.lines().next().unwrap()).unwrap();
210
211 assert_eq!(header["seed"], serde_json::json!(7));
212 assert_eq!(header["schedule"], serde_json::json!("opdms"));
213 assert_eq!(header["condition"], serde_json::json!("world_model"));
214 assert_eq!(header["match_policy"], serde_json::json!("merge"));
215 }
216
217 #[test]
223 fn header_round_trips_diff_policy_stutter_k_optical_merge_tau() {
224 let trace = Trace::new(
225 256,
226 64,
227 1.0,
228 Some(7),
229 "opmd",
230 Condition::Token,
231 MatchPolicy::Merge,
232 DiffPolicy::GraphConditioned,
233 4,
234 Some("householder".to_string()),
235 0.25,
236 None,
237 );
238 let jsonl = trace.to_jsonl();
239 let header: serde_json::Value =
240 serde_json::from_str(jsonl.lines().next().unwrap()).unwrap();
241
242 assert_eq!(header["diff_policy"], serde_json::json!("graph_conditioned"));
243 assert_eq!(header["stutter_k"], serde_json::json!(4));
244 assert_eq!(header["optical"], serde_json::json!("householder"));
245 assert_eq!(header["merge_tau"], serde_json::json!(0.25));
246 assert!(header.get("initial_graph").is_none());
248 }
249
250 #[test]
254 fn header_records_a_non_empty_initial_graph() {
255 let g0 = Graph::seed(crate::graph::GraphNode {
256 id: 0,
257 embedding: vec![0.0; 64],
258 node_type: crate::graph::NodeType::Observation,
259 timestamp: 0,
260 });
261 let trace = Trace::new(
262 256,
263 64,
264 1.0,
265 Some(7),
266 "opmd",
267 Condition::Token,
268 MatchPolicy::Identity,
269 DiffPolicy::Identity,
270 2,
271 None,
272 0.5,
273 Some(g0),
274 );
275 let jsonl = trace.to_jsonl();
276 let header: serde_json::Value =
277 serde_json::from_str(jsonl.lines().next().unwrap()).unwrap();
278
279 let recorded = header
280 .get("initial_graph")
281 .expect("a non-empty G₀ must be recorded");
282 let recorded: Graph = serde_json::from_value(recorded.clone()).unwrap();
283 assert_eq!(recorded.node_count(), 1);
284 }
285
286 #[test]
287 fn header_seed_is_null_when_run_had_none() {
288 let trace = Trace::new(
289 256,
290 64,
291 1.0,
292 None,
293 "opmd",
294 Condition::Token,
295 MatchPolicy::Identity,
296 DiffPolicy::Identity,
297 2,
298 None,
299 0.5,
300 None,
301 );
302 let jsonl = trace.to_jsonl();
303 let header: serde_json::Value =
304 serde_json::from_str(jsonl.lines().next().unwrap()).unwrap();
305 assert!(header["seed"].is_null());
306 }
307}