Skip to main content

fpm_rs/callbacks/
progress.rs

1use crate::{Result, diagnostics::DiagnosticRequest};
2
3use super::{Callback, CallbackAction, CallbackHook, StepContext};
4
5pub struct ProgressLogger {
6    frequency: usize,
7}
8
9impl ProgressLogger {
10    pub fn new(frequency: usize) -> Self {
11        Self {
12            frequency: frequency.max(1),
13        }
14    }
15}
16
17impl Default for ProgressLogger {
18    fn default() -> Self {
19        Self::new(1)
20    }
21}
22
23impl Callback for ProgressLogger {
24    fn requires(&self) -> Vec<DiagnosticRequest> {
25        vec![DiagnosticRequest::Loss]
26    }
27
28    fn requires_for(&self, hook: CallbackHook, iteration: usize) -> Vec<DiagnosticRequest> {
29        if hook == CallbackHook::IterationEnd && iteration.is_multiple_of(self.frequency) {
30            self.requires()
31        } else {
32            Vec::new()
33        }
34    }
35
36    fn on_iteration_end(&mut self, context: &StepContext<'_>) -> Result<CallbackAction> {
37        if context.iteration.is_multiple_of(self.frequency)
38            && let Some(loss) = context.diagnostics.loss
39        {
40            eprintln!("iteration {:>5}: loss {loss:.6e}", context.iteration);
41        }
42        Ok(CallbackAction::Continue)
43    }
44}