use crate::anomaly::AnomalyEvent;
use crate::input::AnalysisSeries;
pub trait AnomalyDetector {
type Error: core::fmt::Debug;
fn fit(&mut self, history: &AnalysisSeries) -> Result<(), Self::Error>;
fn detect(
&mut self,
live: &AnalysisSeries,
next_id: &mut u64,
) -> Result<Vec<AnomalyEvent>, Self::Error>;
}
#[derive(Clone, Debug, Default)]
pub struct StatisticalAnomalyDetector {
pub config: crate::stat_anomaly::StatAnomalyConfig,
pub baseline: Option<crate::stat_anomaly::BaselineStats>,
pub scoped: Option<crate::scoped_baseline::ScopedBaselineStore>,
pub use_scoped: bool,
}
impl StatisticalAnomalyDetector {
#[must_use]
pub const fn new(config: crate::stat_anomaly::StatAnomalyConfig) -> Self {
Self {
config,
baseline: None,
scoped: None,
use_scoped: false,
}
}
pub fn enable_scoped(&mut self, enabled: bool) {
self.use_scoped = enabled;
}
pub fn apply_far_report(&mut self, report: &crate::far_calibrate::FarCalibrationReport) {
self.config = crate::far_calibrate::apply_far_to_stat_config(self.config, report);
}
}
impl AnomalyDetector for StatisticalAnomalyDetector {
type Error = &'static str;
fn fit(&mut self, history: &AnalysisSeries) -> Result<(), Self::Error> {
self.baseline = Some(crate::stat_anomaly::build_baseline(history, self.config));
if self.use_scoped {
self.scoped = Some(crate::scoped_baseline::ScopedBaselineStore::from_series(
history,
self.config,
));
}
Ok(())
}
fn detect(
&mut self,
live: &AnalysisSeries,
next_id: &mut u64,
) -> Result<Vec<AnomalyEvent>, Self::Error> {
if self.use_scoped {
let store = self.scoped.clone().unwrap_or_else(|| {
crate::scoped_baseline::ScopedBaselineStore::from_series(live, self.config)
});
return Ok(crate::scoped_baseline::detect_statistical_scoped(
live,
&store,
self.config,
next_id,
));
}
let baseline = self
.baseline
.clone()
.unwrap_or_else(|| crate::stat_anomaly::build_baseline(live, self.config));
Ok(crate::stat_anomaly::detect_statistical(
live,
&baseline,
self.config,
next_id,
))
}
}