micromegas_datafusion_extensions/histogram/
quantile.rs1use datafusion::{
2 arrow::{
3 array::{Array, Float64Array, Float64Builder, UInt64Array},
4 datatypes::DataType,
5 },
6 error::DataFusionError,
7 logical_expr::{ColumnarValue, ScalarUDF, SimpleScalarUDF},
8 scalar::ScalarValue,
9};
10use std::sync::Arc;
11
12use super::histogram_udaf::HistogramArray;
13use super::otel_codec::{
14 decode_column, estimate_quantile as estimate_otel_quantile, is_otel_blob_type,
15 native_or_otel_signature,
16};
17
18fn estimate_quantile(
19 ratio: f64,
20 start: f64,
21 end: f64,
22 count_values: u64,
23 bins: &UInt64Array,
24) -> f64 {
25 let quant_count = count_values as f64 * ratio;
26 let mut count = 0;
27 for ibin in 0..bins.len() {
28 let this_bucket_count = bins.value(ibin);
29 count += this_bucket_count;
30 if count as f64 >= quant_count && this_bucket_count > 0 {
31 let pop_bucket_start = (count - bins.value(ibin)) as f64;
32 let pop_bucket_end = count as f64;
33 let bucket_ratio =
34 (quant_count - pop_bucket_start) / (pop_bucket_end - pop_bucket_start);
35 let histo_width = end - start;
36 let bucket_width = histo_width / bins.len() as f64;
37 let begin_bucket = start + ibin as f64 * bucket_width;
38 let end_bucket = start + (ibin as f64 + 1.0) * bucket_width;
39 let estimate = (1.0 - bucket_ratio) * begin_bucket + bucket_ratio * end_bucket;
40 return estimate;
41 }
42 }
43 end
44}
45
46fn otel_quantile_from_histogram(
47 values: &[ColumnarValue],
48) -> Result<ColumnarValue, DataFusionError> {
49 if let ColumnarValue::Scalar(scalar_value) = &values[1]
50 && !matches!(scalar_value, ScalarValue::Float64(Some(_)))
51 {
52 return Err(DataFusionError::Execution(format!(
53 "bad ratio {scalar_value:?} in quantile_from_histogram"
54 )));
55 }
56 let arrays = ColumnarValue::values_to_arrays(values)?;
57 let histograms = decode_column("quantile_from_histogram", &arrays[0])?;
58 let ratios = arrays[1]
59 .as_any()
60 .downcast_ref::<Float64Array>()
61 .ok_or_else(|| DataFusionError::Internal("downcasting to Float64Array".into()))?;
62 let mut result_builder = Float64Builder::with_capacity(histograms.len());
63 for (i, histogram) in histograms.iter().enumerate() {
64 let estimate = if ratios.is_null(i) {
65 None
66 } else {
67 histogram
68 .as_ref()
69 .and_then(|h| estimate_otel_quantile(h, ratios.value(i)))
70 };
71 result_builder.append_option(estimate);
72 }
73 Ok(ColumnarValue::Array(Arc::new(result_builder.finish())))
74}
75
76fn quantile_from_histogram(values: &[ColumnarValue]) -> Result<ColumnarValue, DataFusionError> {
77 if values.len() != 2 {
78 return Err(DataFusionError::Execution(
79 "wrong number of arguments to quantile_from_histogram".into(),
80 ));
81 }
82
83 if is_otel_blob_type(&values[0].data_type()) {
84 return otel_quantile_from_histogram(values);
85 }
86
87 let histo_array: HistogramArray = (&values[0]).try_into()?;
88 let mut result_builder = Float64Builder::with_capacity(histo_array.len());
89 for index_histo in 0..histo_array.len() {
90 if histo_array.is_null_at(index_histo) {
91 result_builder.append_null();
92 continue;
93 }
94 let ratio = match &values[1] {
95 ColumnarValue::Array(array) => array
96 .as_any()
97 .downcast_ref::<Float64Array>()
98 .ok_or_else(|| DataFusionError::Internal("downcasting to Float64Array".into()))?
99 .value(index_histo),
100 ColumnarValue::Scalar(scalar_value) => {
101 if let ScalarValue::Float64(Some(ratio)) = scalar_value {
102 *ratio
103 } else {
104 return Err(DataFusionError::Execution(format!(
105 "bad ratio {scalar_value:?} in quantile_from_histogram"
106 )));
107 }
108 }
109 };
110
111 let bins = histo_array.get_bins(index_histo)?;
112 result_builder.append_value(estimate_quantile(
113 ratio,
114 histo_array.get_start(index_histo)?,
115 histo_array.get_end(index_histo)?,
116 histo_array.get_count(index_histo)?,
117 &bins,
118 ));
119 }
120
121 Ok(ColumnarValue::Array(Arc::new(result_builder.finish())))
122}
123
124pub fn make_quantile_from_histogram_udf() -> ScalarUDF {
128 ScalarUDF::from(SimpleScalarUDF::new_with_signature(
129 "quantile_from_histogram",
130 native_or_otel_signature(&[DataType::Float64]),
131 DataType::Float64,
132 Arc::new(&quantile_from_histogram),
133 ))
134}