1use core::cmp::Ordering;
2use std::{
3 fmt::Display,
4 path::{Path, PathBuf},
5};
6
7use crate::{
8 logger::FileMetricLogger,
9 metric::store::{Aggregate, EventStore, LogEventStore, Split},
10};
11
12pub struct MetricEntry {
14 pub step: usize,
16 pub value: f64,
18}
19
20pub struct MetricSummary {
22 pub name: String,
24 pub entries: Vec<MetricEntry>,
26}
27
28impl MetricSummary {
29 fn new<E: EventStore>(
30 event_store: &mut E,
31 metric: &str,
32 split: Split,
33 num_epochs: usize,
34 ) -> Option<Self> {
35 let entries = (1..=num_epochs)
36 .filter_map(|epoch| {
37 event_store
38 .find_metric(metric, epoch, Aggregate::Mean, split)
39 .map(|value| MetricEntry { step: epoch, value })
40 })
41 .collect::<Vec<_>>();
42
43 if entries.is_empty() {
44 None
45 } else {
46 Some(Self {
47 name: metric.to_string(),
48 entries,
49 })
50 }
51 }
52}
53
54pub struct SummaryMetrics {
56 pub train: Vec<MetricSummary>,
58 pub valid: Vec<MetricSummary>,
60}
61
62pub struct LearnerSummary {
64 pub epochs: usize,
66 pub metrics: SummaryMetrics,
68 pub(crate) model: Option<String>,
70}
71
72impl LearnerSummary {
73 pub fn new<S: AsRef<str>>(directory: impl AsRef<Path>, metrics: &[S]) -> Result<Self, String> {
80 let directory = directory.as_ref();
81 if !directory.exists() {
82 return Err(format!(
83 "Artifact directory does not exist at: {}",
84 directory.display()
85 ));
86 }
87
88 let mut event_store = LogEventStore::default();
89
90 let logger = FileMetricLogger::new(directory);
91 if !logger.split_exists(Split::Train) && !logger.split_exists(Split::Valid) {
92 return Err(format!(
93 "No training or validation artifacts found at: {}",
94 directory.display()
95 ));
96 }
97
98 let epochs = logger.epochs();
100
101 event_store.register_logger(logger);
102
103 let train_summary = metrics
104 .iter()
105 .filter_map(|metric| {
106 MetricSummary::new(&mut event_store, metric.as_ref(), Split::Train, epochs)
107 })
108 .collect::<Vec<_>>();
109
110 let valid_summary = metrics
111 .iter()
112 .filter_map(|metric| {
113 MetricSummary::new(&mut event_store, metric.as_ref(), Split::Valid, epochs)
114 })
115 .collect::<Vec<_>>();
116
117 Ok(Self {
118 epochs,
119 metrics: SummaryMetrics {
120 train: train_summary,
121 valid: valid_summary,
122 },
123 model: None,
124 })
125 }
126
127 pub(crate) fn with_model(mut self, name: String) -> Self {
128 self.model = Some(name);
129 self
130 }
131}
132
133impl Display for LearnerSummary {
134 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
135 let split_train = "Train";
137 let split_valid = "Valid";
138 let max_split_len = "Split".len().max(split_train.len()).max(split_valid.len());
139 let mut max_metric_len = "Metric".len();
140 for metric in self.metrics.train.iter() {
141 max_metric_len = max_metric_len.max(metric.name.len());
142 }
143 for metric in self.metrics.valid.iter() {
144 max_metric_len = max_metric_len.max(metric.name.len());
145 }
146
147 writeln!(
149 f,
150 "{:=>width_symbol$} Learner Summary {:=>width_symbol$}",
151 "",
152 "",
153 width_symbol = 24,
154 )?;
155
156 if let Some(model) = &self.model {
157 writeln!(f, "Model:\n{model}")?;
158 }
159 writeln!(f, "Total Epochs: {epochs}\n\n", epochs = self.epochs)?;
160
161 writeln!(
163 f,
164 "| {:<width_split$} | {:<width_metric$} | Min. | Epoch | Max. | Epoch |\n|{:->width_split$}--|{:->width_metric$}--|----------|----------|----------|----------|",
165 "Split",
166 "Metric",
167 "",
168 "",
169 width_split = max_split_len,
170 width_metric = max_metric_len,
171 )?;
172
173 fn cmp_f64(a: &f64, b: &f64) -> Ordering {
175 match (a.is_nan(), b.is_nan()) {
176 (true, true) => Ordering::Equal,
177 (true, false) => Ordering::Greater,
178 (false, true) => Ordering::Less,
179 _ => a.partial_cmp(b).unwrap(),
180 }
181 }
182
183 fn fmt_val(val: f64) -> String {
184 if val < 1e-2 {
185 format!("{val:<9.3e}")
187 } else {
188 format!("{val:<9.3}")
189 }
190 }
191
192 let mut write_metrics_summary =
193 |metrics: &[MetricSummary], split: &str| -> std::fmt::Result {
194 for metric in metrics.iter() {
195 if metric.entries.is_empty() {
196 continue; }
198
199 let metric_min = metric
201 .entries
202 .iter()
203 .min_by(|a, b| cmp_f64(&a.value, &b.value))
204 .unwrap();
205 let metric_max = metric
206 .entries
207 .iter()
208 .max_by(|a, b| cmp_f64(&a.value, &b.value))
209 .unwrap();
210
211 writeln!(
212 f,
213 "| {:<width_split$} | {:<width_metric$} | {}| {:<9?}| {}| {:<9?}|",
214 split,
215 metric.name,
216 fmt_val(metric_min.value),
217 metric_min.step,
218 fmt_val(metric_max.value),
219 metric_max.step,
220 width_split = max_split_len,
221 width_metric = max_metric_len,
222 )?;
223 }
224
225 Ok(())
226 };
227
228 write_metrics_summary(&self.metrics.train, split_train)?;
229 write_metrics_summary(&self.metrics.valid, split_valid)?;
230
231 Ok(())
232 }
233}
234
235#[derive(Clone)]
236pub struct LearnerSummaryConfig {
238 pub(crate) directory: PathBuf,
239 pub(crate) metrics: Vec<String>,
240}
241
242impl LearnerSummaryConfig {
243 pub fn init(&self) -> Result<LearnerSummary, String> {
245 LearnerSummary::new(&self.directory, &self.metrics[..])
246 }
247}
248
249#[cfg(test)]
250mod tests {
251 use super::*;
252
253 #[test]
254 #[should_panic = "Summary artifacts should exist"]
255 fn test_artifact_dir_should_exist() {
256 let dir = "/tmp/learner-summary-not-found";
257 let _summary = LearnerSummary::new(dir, &["Loss"]).expect("Summary artifacts should exist");
258 }
259
260 #[test]
261 #[should_panic = "Summary artifacts should exist"]
262 fn test_train_valid_artifacts_should_exist() {
263 let dir = "/tmp/test-learner-summary-empty";
264 std::fs::create_dir_all(dir).ok();
265 let _summary = LearnerSummary::new(dir, &["Loss"]).expect("Summary artifacts should exist");
266 }
267
268 #[test]
269 fn test_summary_should_be_empty() {
270 let dir = Path::new("/tmp/test-learner-summary-empty-metrics");
271 std::fs::create_dir_all(dir).unwrap();
272 std::fs::create_dir_all(dir.join("train/epoch-1")).unwrap();
273 std::fs::create_dir_all(dir.join("valid/epoch-1")).unwrap();
274 let summary = LearnerSummary::new(dir.to_str().unwrap(), &["Loss"])
275 .expect("Summary artifacts should exist");
276
277 assert_eq!(summary.epochs, 1);
278
279 assert_eq!(summary.metrics.train.len(), 0);
280 assert_eq!(summary.metrics.valid.len(), 0);
281
282 std::fs::remove_dir_all(dir).unwrap();
283 }
284
285 #[test]
286 fn test_summary_should_be_collected() {
287 let dir = Path::new("/tmp/test-learner-summary");
288 let train_dir = dir.join("train/epoch-1");
289 let valid_dir = dir.join("valid/epoch-1");
290 std::fs::create_dir_all(dir).unwrap();
291 std::fs::create_dir_all(&train_dir).unwrap();
292 std::fs::create_dir_all(&valid_dir).unwrap();
293
294 std::fs::write(train_dir.join("Loss.log"), "1.0\n2.0").expect("Unable to write file");
295 std::fs::write(valid_dir.join("Loss.log"), "1.0").expect("Unable to write file");
296
297 let summary = LearnerSummary::new(dir.to_str().unwrap(), &["Loss"])
298 .expect("Summary artifacts should exist");
299
300 assert_eq!(summary.epochs, 1);
301
302 assert_eq!(summary.metrics.train.len(), 1);
304 assert_eq!(summary.metrics.valid.len(), 1);
305
306 let train_metric = &summary.metrics.train[0];
308 assert_eq!(train_metric.name, "Loss");
309 assert_eq!(train_metric.entries.len(), 1);
310 let entry = &train_metric.entries[0];
311 assert_eq!(entry.step, 1); assert_eq!(entry.value, 1.5); let valid_metric = &summary.metrics.valid[0];
316 assert_eq!(valid_metric.name, "Loss");
317 assert_eq!(valid_metric.entries.len(), 1);
318 let entry = &valid_metric.entries[0];
319 assert_eq!(entry.step, 1); assert_eq!(entry.value, 1.0);
321
322 std::fs::remove_dir_all(dir).unwrap();
323 }
324}