Skip to main content

ergo_runtime/compute/implementations/mean/
impl.rs

1use std::collections::HashMap;
2
3use crate::common::Value;
4use crate::compute::{ComputeError, ComputePrimitive, ComputePrimitiveManifest, PrimitiveState};
5
6use super::manifest::mean_manifest;
7
8pub struct Mean {
9    manifest: ComputePrimitiveManifest,
10}
11
12impl Mean {
13    pub fn new() -> Self {
14        Self {
15            manifest: mean_manifest(),
16        }
17    }
18}
19
20impl Default for Mean {
21    fn default() -> Self {
22        Self::new()
23    }
24}
25
26impl ComputePrimitive for Mean {
27    fn manifest(&self) -> &ComputePrimitiveManifest {
28        &self.manifest
29    }
30
31    fn compute(
32        &self,
33        inputs: &HashMap<String, Value>,
34        _parameters: &HashMap<String, Value>,
35        _state: Option<&mut PrimitiveState>,
36    ) -> Result<HashMap<String, Value>, ComputeError> {
37        let series = inputs
38            .get("series")
39            .and_then(|v| v.as_series())
40            .expect("missing required series input 'series'");
41
42        let result = if series.is_empty() {
43            0.0
44        } else {
45            let sum: f64 = series.iter().copied().sum();
46            let mean = sum / (series.len() as f64);
47            if !mean.is_finite() {
48                return Err(ComputeError::NonFiniteResult);
49            }
50            mean
51        };
52
53        Ok(HashMap::from([(
54            "result".to_string(),
55            Value::Number(result),
56        )]))
57    }
58}