|
| 1 | +//! Implementation of a Wasm component that can perform changepoint detection on time series. |
| 2 | +
|
| 3 | +use std::{fmt, num::NonZeroUsize}; |
| 4 | + |
| 5 | +use augurs_changepoint::{ |
| 6 | + self, dist::NormalGamma, BocpdDetector, DefaultArgpcpDetector, DefaultArgpcpDetectorBuilder, |
| 7 | + Detector, |
| 8 | +}; |
| 9 | + |
| 10 | +// Wrap the wit-bindgen macro in a module so we don't get warned about missing docs in the generated trait. |
| 11 | +mod bindings { |
| 12 | + wit_bindgen::generate!({ |
| 13 | + world: "changepoint", |
| 14 | + default_bindings_module: "bindings", |
| 15 | + }); |
| 16 | +} |
| 17 | +use crate::bindings::{ |
| 18 | + export, |
| 19 | + grafana::augurs::types::{Algorithm, ArgpcpParams, Input, NormalGammaParams, Output}, |
| 20 | + Guest, |
| 21 | +}; |
| 22 | + |
| 23 | +struct ChangepointWorld; |
| 24 | +export!(ChangepointWorld); |
| 25 | + |
| 26 | +impl Guest for ChangepointWorld { |
| 27 | + fn detect(input: Input) -> Result<Output, String> { |
| 28 | + detect(input).map_err(|e| e.to_string()) |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +/// An error type for the changepoint detector. |
| 33 | +#[derive(Debug)] |
| 34 | +pub enum ChangepointError { |
| 35 | + /// An invalid parameter was provided to the Normal Gamma distribution. |
| 36 | + NormalGammaError(augurs_changepoint::dist::NormalGammaError), |
| 37 | + /// An overflow occurred when converting an integer to a `NonZeroUsize`. |
| 38 | + TryFromIntError(std::num::TryFromIntError), |
| 39 | + /// An invalid parameter was provided to the max lag. |
| 40 | + InvalidMaxLag(u32), |
| 41 | +} |
| 42 | + |
| 43 | +impl From<std::num::TryFromIntError> for ChangepointError { |
| 44 | + fn from(value: std::num::TryFromIntError) -> Self { |
| 45 | + Self::TryFromIntError(value) |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +impl From<augurs_changepoint::dist::NormalGammaError> for ChangepointError { |
| 50 | + fn from(value: augurs_changepoint::dist::NormalGammaError) -> Self { |
| 51 | + Self::NormalGammaError(value) |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +impl fmt::Display for ChangepointError { |
| 56 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 57 | + match self { |
| 58 | + Self::NormalGammaError(e) => write!(f, "invalid Normal Gamma distribution: {}", e), |
| 59 | + Self::TryFromIntError(e) => write!(f, "overflow converting to u32: {}", e), |
| 60 | + Self::InvalidMaxLag(ml) => write!(f, "invalid max lag: {}", ml), |
| 61 | + } |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +impl std::error::Error for ChangepointError {} |
| 66 | + |
| 67 | +impl TryFrom<ArgpcpParams> for DefaultArgpcpDetectorBuilder { |
| 68 | + type Error = ChangepointError; |
| 69 | + |
| 70 | + fn try_from(params: ArgpcpParams) -> Result<Self, Self::Error> { |
| 71 | + let mut builder = DefaultArgpcpDetector::builder(); |
| 72 | + if let Some(cv) = params.constant_value { |
| 73 | + builder = builder.constant_value(cv); |
| 74 | + } |
| 75 | + if let Some(ls) = params.length_scale { |
| 76 | + builder = builder.length_scale(ls); |
| 77 | + } |
| 78 | + if let Some(nl) = params.noise_level { |
| 79 | + builder = builder.noise_level(nl); |
| 80 | + } |
| 81 | + if let Some(ml) = params.max_lag { |
| 82 | + let ml = NonZeroUsize::new(ml.try_into().map_err(ChangepointError::TryFromIntError)?) |
| 83 | + .ok_or(ChangepointError::InvalidMaxLag(ml))?; |
| 84 | + builder = builder.max_lag(ml); |
| 85 | + } |
| 86 | + if let Some(a0) = params.alpha0 { |
| 87 | + builder = builder.alpha0(a0); |
| 88 | + } |
| 89 | + if let Some(b0) = params.beta0 { |
| 90 | + builder = builder.beta0(b0); |
| 91 | + } |
| 92 | + if let Some(h) = params.logistic_hazard.h { |
| 93 | + builder = builder.logistic_hazard_h(h); |
| 94 | + } |
| 95 | + if let Some(a) = params.logistic_hazard.a { |
| 96 | + builder = builder.logistic_hazard_a(a); |
| 97 | + } |
| 98 | + if let Some(b) = params.logistic_hazard.b { |
| 99 | + builder = builder.logistic_hazard_b(b); |
| 100 | + } |
| 101 | + Ok(builder) |
| 102 | + } |
| 103 | +} |
| 104 | + |
| 105 | +fn convert_normal_gamma( |
| 106 | + params: Option<NormalGammaParams>, |
| 107 | +) -> Result<NormalGamma, ChangepointError> { |
| 108 | + Ok(NormalGamma::new( |
| 109 | + params.map(|p| p.mu).flatten().unwrap_or(0.0), |
| 110 | + params.map(|p| p.rho).flatten().unwrap_or(1.0), |
| 111 | + params.map(|p| p.s).flatten().unwrap_or(1.0), |
| 112 | + params.map(|p| p.v).flatten().unwrap_or(1.0), |
| 113 | + )?) |
| 114 | +} |
| 115 | + |
| 116 | +fn detect(input: Input) -> Result<Output, ChangepointError> { |
| 117 | + match input.algorithm { |
| 118 | + Algorithm::Argpcp(params) => Ok(DefaultArgpcpDetectorBuilder::try_from(params)? |
| 119 | + .build() |
| 120 | + .detect_changepoints(&input.data) |
| 121 | + .into_iter() |
| 122 | + .map(|i| i.try_into()) |
| 123 | + .collect::<Result<_, _>>()?), |
| 124 | + Algorithm::Bocpd(params) => Ok(BocpdDetector::normal_gamma( |
| 125 | + params.hazard_lambda.unwrap_or(250.0), |
| 126 | + convert_normal_gamma(params.normal_gamma_params)?, |
| 127 | + ) |
| 128 | + .detect_changepoints(&input.data) |
| 129 | + .into_iter() |
| 130 | + .map(|i| i.try_into()) |
| 131 | + .collect::<Result<_, _>>()?), |
| 132 | + } |
| 133 | +} |
0 commit comments