augurs_js/ets.rs
1//! JavaScript bindings for the AutoETS model.
2
3use js_sys::Float64Array;
4use wasm_bindgen::prelude::*;
5
6/// Automatic ETS model selection.
7#[derive(Debug)]
8#[wasm_bindgen]
9pub struct AutoETS {
10 /// The inner model search instance.
11 inner: augurs_ets::AutoETS,
12}
13
14#[wasm_bindgen]
15impl AutoETS {
16 /// Create a new `AutoETS` model search instance.
17 ///
18 /// # Errors
19 ///
20 /// If the `spec` string is invalid, this function returns an error.
21 #[wasm_bindgen(constructor)]
22 pub fn new(season_length: usize, spec: String) -> Result<AutoETS, JsValue> {
23 let inner =
24 augurs_ets::AutoETS::new(season_length, spec.as_str()).map_err(|e| e.to_string())?;
25 Ok(Self { inner })
26 }
27
28 /// Search for the best model, fitting it to the data.
29 ///
30 /// The model will be stored on the inner `AutoETS` instance, after which
31 /// forecasts can be produced using its `predict` method.
32 ///
33 /// # Errors
34 ///
35 /// If no model can be found, or if any parameters are invalid, this function
36 /// returns an error.
37 #[wasm_bindgen]
38 pub fn fit(&mut self, y: Float64Array) -> Result<(), JsValue> {
39 self.inner.fit(&y.to_vec()).map_err(|e| e.to_string())?;
40 Ok(())
41 }
42
43 /// Predict the next `horizon` values using the best model, optionally including
44 /// prediction intervals at the specified level.
45 ///
46 /// `level` should be a float between 0 and 1 representing the confidence level.
47 ///
48 /// # Errors
49 ///
50 /// This function will return an error if no model has been fit yet (using [`AutoETS::fit`]).
51 pub fn predict(&self, horizon: usize, level: Option<f64>) -> Result<JsValue, JsValue> {
52 let forecasts = self
53 .inner
54 .predict(horizon, level)
55 .map_err(|e| e.to_string())?;
56 Ok(serde_wasm_bindgen::to_value(&forecasts)
57 .map_err(|e| format!("serializing forecasts: {e}"))?)
58 }
59}