1use serde::{Deserialize, Serialize};
4use std::fs;
5use std::io;
6use std::path::Path;
7
8#[derive(Clone, Copy, Debug)]
10pub enum StatsFormat {
11 Toml,
12 Json,
13}
14
15impl StatsFormat {
16 pub fn from_path(path: &Path) -> io::Result<Self> {
17 match path.extension().and_then(|extension| extension.to_str()) {
18 Some("toml") => Ok(Self::Toml),
19 Some("json") => Ok(Self::Json),
20 _ => Err(io::Error::new(
21 io::ErrorKind::InvalidInput,
22 "statistics path must have a .toml or .json extension",
23 )),
24 }
25 }
26}
27
28fn quoted_toml_string(value: &str) -> String {
29 toml::Value::String(value.to_string()).to_string()
30}
31
32pub fn canonical_float(value: f64) -> String {
33 let rounded = (value * 1_000_000.0).round() / 1_000_000.0;
34 let mut rendered = format!("{rounded:.6}");
35 while rendered.ends_with('0') {
36 rendered.pop();
37 }
38 if rendered.ends_with('.') {
39 rendered.push('0');
40 }
41 if rendered == "-0.0" {
42 "0.0".to_string()
43 } else {
44 rendered
45 }
46}
47
48fn canonical_rule_key(rule: &str) -> String {
49 if !rule.is_empty()
50 && rule
51 .chars()
52 .all(|character| character.is_ascii_alphanumeric() || matches!(character, '_' | '-'))
53 {
54 rule.to_string()
55 } else {
56 quoted_toml_string(rule)
57 }
58}
59
60pub(super) fn deserialise_expected_time<'de, D>(deserializer: D) -> Result<Option<u64>, D::Error>
61where
62 D: serde::Deserializer<'de>,
63{
64 Option::<u64>::deserialize(deserializer)
65}
66
67#[derive(Clone, Debug, Eq, PartialEq)]
69pub struct RecordedRunConfig {
70 pub rewriter: String,
71 pub comprehension_expander: String,
72 pub heuristic: String,
73 pub channelling: String,
74 pub seed: u64,
75 pub solver_seed: u32,
76 pub solver: String,
77}
78
79fn rule_trace_rules_by_count_desc(
80 rules: &std::collections::BTreeMap<String, u64>,
81) -> Vec<(&String, u64)> {
82 let mut sorted_rules: Vec<_> = rules.iter().map(|(rule, count)| (rule, *count)).collect();
83 sorted_rules.sort_by(|(name_a, count_a), (name_b, count_b)| {
84 count_b.cmp(count_a).then_with(|| name_a.cmp(name_b))
85 });
86 sorted_rules
87}
88
89#[derive(Deserialize, Serialize, Debug, Default)]
91#[serde(default)]
92#[serde(deny_unknown_fields)]
93pub struct TestRunStats {
94 #[serde(skip_serializing_if = "Option::is_none")]
96 pub status: Option<String>,
97
98 #[serde(
100 default,
101 rename = "expected-time",
102 skip_serializing_if = "Option::is_none",
103 deserialize_with = "deserialise_expected_time"
104 )]
105 pub expected_time: Option<u64>,
106
107 #[serde(skip_serializing_if = "RecordedToolStats::is_empty")]
109 pub conjure: RecordedToolStats,
110
111 pub runs: Vec<RecordedRunStats>,
113}
114
115#[derive(Deserialize, Serialize, Debug, Default)]
117#[serde(default, deny_unknown_fields, rename_all = "kebab-case")]
118pub struct RecordedRunStats {
119 pub rewriter: String,
120 pub comprehension_expander: String,
121 pub heuristic: String,
122 pub channelling: String,
123 pub seed: u64,
124 pub solver_seed: u32,
125 pub solver: String,
126 pub case_name: String,
127 pub model_index: usize,
128 pub choice_path: Vec<usize>,
130 pub choices: Vec<String>,
131 pub representations: Vec<String>,
133 #[serde(skip_serializing_if = "Option::is_none")]
134 pub minion_discrete_threshold: Option<usize>,
135 pub sat_encoding_amo: Vec<String>,
136 pub sat_encoding_cardinality: Vec<String>,
137 pub sat_encoding_pb: Vec<String>,
138 pub sat_encoding_table: Vec<String>,
139 pub sat_encoding_element: Vec<String>,
140 pub sat_encoding_alldifferent: Vec<String>,
141 pub status: String,
142 #[serde(skip_serializing_if = "Option::is_none")]
144 pub solution_limit: Option<i32>,
145 #[serde(skip_serializing_if = "Option::is_none")]
147 pub translation_time: Option<f64>,
148 #[serde(skip_serializing_if = "Option::is_none")]
150 pub solve_time: Option<f64>,
151 #[serde(skip_serializing_if = "Option::is_none")]
152 pub backend_time: Option<f64>,
153 #[serde(skip_serializing_if = "Option::is_none")]
155 pub search_time: Option<f64>,
156 #[serde(skip_serializing_if = "Option::is_none")]
157 pub solution_processing_time: Option<f64>,
158 #[serde(skip_serializing_if = "RecordedRuleTraceStats::is_empty")]
160 pub rule_trace: RecordedRuleTraceStats,
161}
162
163#[derive(Deserialize, Serialize, Debug, Default)]
165#[serde(default)]
166#[serde(deny_unknown_fields)]
167pub struct RecordedRuleTraceStats {
168 #[serde(rename = "attempts", skip_serializing_if = "Option::is_none")]
169 pub total_rule_attempts: Option<u64>,
170 #[serde(rename = "applications", skip_serializing_if = "Option::is_none")]
171 pub total_rule_applications: Option<u64>,
172 #[serde(skip_serializing_if = "std::collections::BTreeMap::is_empty")]
173 pub rules: std::collections::BTreeMap<String, u64>,
174}
175
176impl RecordedRuleTraceStats {
177 fn is_empty(&self) -> bool {
178 self.total_rule_attempts.is_none()
179 && self.total_rule_applications.is_none()
180 && self.rules.is_empty()
181 }
182}
183
184pub fn read_stats_or_default(path: &Path) -> io::Result<TestRunStats> {
185 if path.exists() {
186 let contents = fs::read_to_string(path)?;
187 match StatsFormat::from_path(path)? {
188 StatsFormat::Toml => toml::from_str(&contents)
189 .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err)),
190 StatsFormat::Json => serde_json::from_str(&contents)
191 .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err)),
192 }
193 } else {
194 Ok(TestRunStats::default())
195 }
196}
197
198#[derive(Deserialize, Serialize, Debug, Default)]
200#[serde(default)]
201#[serde(deny_unknown_fields)]
202pub struct RecordedToolStats {
203 #[serde(skip_serializing_if = "Option::is_none")]
205 pub status: Option<String>,
206
207 #[serde(rename = "translation-time", skip_serializing_if = "Option::is_none")]
209 pub translation_time: Option<f64>,
210
211 #[serde(rename = "solve-time", skip_serializing_if = "Option::is_none")]
213 pub solve_time: Option<f64>,
214
215 #[serde(rename = "wall-clock-time", skip_serializing_if = "Option::is_none")]
217 pub wall_clock_time: Option<f64>,
218
219 #[serde(
221 rename = "conjure-translation-time",
222 skip_serializing_if = "Option::is_none"
223 )]
224 pub conjure_translation_time: Option<f64>,
225
226 #[serde(
228 rename = "savilerow-translation-time",
229 skip_serializing_if = "Option::is_none"
230 )]
231 pub savilerow_translation_time: Option<f64>,
232}
233
234impl RecordedToolStats {
235 fn is_empty(&self) -> bool {
236 self.status.is_none()
237 && self.translation_time.is_none()
238 && self.solve_time.is_none()
239 && self.wall_clock_time.is_none()
240 && self.conjure_translation_time.is_none()
241 && self.savilerow_translation_time.is_none()
242 }
243}
244
245pub fn replace_config_run_stats(
247 path: &Path,
248 config: &RecordedRunConfig,
249 rows: Vec<RecordedRunStats>,
250) -> io::Result<()> {
251 update_canonical_stats(path, |stats| {
252 stats.runs.retain(|row| {
253 !(row.rewriter == config.rewriter
254 && row.comprehension_expander == config.comprehension_expander
255 && row.heuristic == config.heuristic
256 && row.channelling == config.channelling
257 && row.seed == config.seed
258 && row.solver_seed == config.solver_seed
259 && row.solver == config.solver)
260 });
261 stats.runs.extend(rows);
262 stats.runs.sort_by(|a, b| {
263 (
264 &a.rewriter,
265 &a.comprehension_expander,
266 &a.heuristic,
267 &a.channelling,
268 a.seed,
269 a.solver_seed,
270 &a.solver,
271 a.model_index,
272 )
273 .cmp(&(
274 &b.rewriter,
275 &b.comprehension_expander,
276 &b.heuristic,
277 &b.channelling,
278 b.seed,
279 b.solver_seed,
280 &b.solver,
281 b.model_index,
282 ))
283 });
284 })
285}
286
287pub fn update_canonical_stats(
288 path: &Path,
289 update: impl FnOnce(&mut TestRunStats),
290) -> io::Result<()> {
291 let mut stats = read_stats_or_default(path)?;
292 update(&mut stats);
293 write_stats(path, &stats)
294}
295
296pub fn write_stats(path: &Path, stats: &TestRunStats) -> io::Result<()> {
298 match StatsFormat::from_path(path)? {
299 StatsFormat::Toml => write_canonical_stats(path, stats),
300 StatsFormat::Json => {
301 let contents = serde_json::to_string_pretty(stats)
302 .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?;
303 fs::write(path, format!("{contents}\n"))
304 }
305 }
306}
307
308fn push_optional_float(contents: &mut String, key: &str, value: Option<f64>) {
309 if let Some(value) = value {
310 contents.push_str(key);
311 contents.push_str(" = ");
312 contents.push_str(&canonical_float(value));
313 contents.push('\n');
314 }
315}
316
317pub fn write_canonical_stats(path: &Path, stats: &TestRunStats) -> io::Result<()> {
318 let mut contents = String::new();
319
320 if let Some(expected_time) = stats.expected_time {
321 contents.push_str(&format!("expected-time = {expected_time}\n"));
322 }
323 if let Some(status) = &stats.status {
324 contents.push_str(&format!("status = {}\n", quoted_toml_string(status)));
325 }
326
327 let conjure = &stats.conjure;
328 if !conjure.is_empty() {
329 if !contents.is_empty() {
330 contents.push('\n');
331 }
332 contents.push_str("[conjure]\n");
333 if let Some(status) = &conjure.status {
334 contents.push_str(&format!("status = {}\n", quoted_toml_string(status)));
335 }
336 push_optional_float(&mut contents, "wall-clock-time", conjure.wall_clock_time);
337 push_optional_float(&mut contents, "translation-time", conjure.translation_time);
338 push_optional_float(
339 &mut contents,
340 "conjure-translation-time",
341 conjure.conjure_translation_time,
342 );
343 push_optional_float(
344 &mut contents,
345 "savilerow-translation-time",
346 conjure.savilerow_translation_time,
347 );
348 push_optional_float(&mut contents, "solve-time", conjure.solve_time);
349 }
350
351 for run in &stats.runs {
352 contents.push_str("\n[[runs]]\n");
353 let rendered =
354 toml::to_string(run).map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?;
355 let mut document: toml_edit::DocumentMut = rendered
356 .parse()
357 .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?;
358 document.remove("rule-trace");
361 contents.push_str(document.to_string().trim_end());
362 contents.push('\n');
363
364 if run.rule_trace.total_rule_attempts.is_some()
365 || run.rule_trace.total_rule_applications.is_some()
366 || !run.rule_trace.rules.is_empty()
367 {
368 contents.push('\n');
369 }
370 if let Some(attempts) = run.rule_trace.total_rule_attempts {
371 contents.push_str(&format!("rule-trace.attempts = {attempts}\n"));
372 }
373 if let Some(applications) = run.rule_trace.total_rule_applications {
374 contents.push_str(&format!("rule-trace.applications = {applications}\n"));
375 }
376 for (rule, count) in rule_trace_rules_by_count_desc(&run.rule_trace.rules) {
377 contents.push_str(&format!(
378 "rule-trace.rules.{} = {count}\n",
379 canonical_rule_key(rule)
380 ));
381 }
382 }
383
384 fs::write(path, contents)
385}