Skip to main content

micromegas_datafusion_extensions/histogram/
variance.rs

1use super::histogram_udaf::HistogramArray;
2use super::otel_codec::{decode_column, is_otel_blob_type, native_or_otel_signature};
3use datafusion::{
4    arrow::{array::Float64Builder, datatypes::DataType},
5    error::DataFusionError,
6    logical_expr::{ColumnarValue, ScalarUDF, SimpleScalarUDF},
7};
8use std::sync::Arc;
9
10fn compute_variance(n: f64, sum: f64, sum_sq: f64) -> f64 {
11    let mean = sum / n;
12    ((sum_sq / n) - (mean * mean)) * (n / (n - 1.0))
13}
14
15fn variance_from_histogram(values: &[ColumnarValue]) -> Result<ColumnarValue, DataFusionError> {
16    if values.len() != 1 {
17        return Err(DataFusionError::Execution(
18            "wrong number of arguments to variance_from_histogram".into(),
19        ));
20    }
21
22    // OTLP histograms carry no sum of squares, so there is nothing to estimate a variance from.
23    if is_otel_blob_type(&values[0].data_type()) {
24        let arrays = ColumnarValue::values_to_arrays(values)?;
25        let histograms = decode_column("variance_from_histogram", &arrays[0])?;
26        let mut result_builder = Float64Builder::with_capacity(histograms.len());
27        result_builder.append_nulls(histograms.len());
28        return Ok(ColumnarValue::Array(Arc::new(result_builder.finish())));
29    }
30
31    let histo_array: HistogramArray = (&values[0]).try_into()?;
32    let mut result_builder = Float64Builder::with_capacity(histo_array.len());
33    for index_histo in 0..histo_array.len() {
34        if histo_array.is_null_at(index_histo) {
35            result_builder.append_null();
36            continue;
37        }
38        result_builder.append_value(compute_variance(
39            histo_array.get_count(index_histo)? as f64,
40            histo_array.get_sum(index_histo)?,
41            histo_array.get_sum_sq(index_histo)?,
42        ));
43    }
44
45    Ok(ColumnarValue::Array(Arc::new(result_builder.finish())))
46}
47/// Creates a user-defined function to compute the variance from a histogram.
48///
49/// Accepts the native histogram struct, or an `otel_histograms.histogram` blob (always NULL).
50pub fn make_variance_from_histogram_udf() -> ScalarUDF {
51    ScalarUDF::from(SimpleScalarUDF::new_with_signature(
52        "variance_from_histogram",
53        native_or_otel_signature(&[]),
54        DataType::Float64,
55        Arc::new(&variance_from_histogram),
56    ))
57}