1mod broadcast;
21mod comparison;
22#[cfg(test)]
23mod tests;
24
25pub(crate) use broadcast::validate_scalar;
26pub use broadcast::{
27 ParameterizedMath, ScalarSeriesOperand, map_arithmetic_series, map_compare_series,
28 map_math_with_parameters,
29};
30pub use comparison::{Comparison, ComparisonOp, map_compare_literal};
31
32use std::f64::consts::PI;
33use std::sync::Arc;
34
35use datafusion::error::{DataFusionError, Result};
36use datatypes::arrow::array::{Float64Array, Float64Builder, UInt32Builder};
37use datatypes::series::histogram::HistogramBatchBuilder;
38use datatypes::series::samples::{
39 DenseSamplesRef, HistogramSamples, SampleRef, Samples, Series, SeriesFields, SeriesSchema,
40};
41use datatypes::series::time::{GridRange, TimeAxis};
42use datatypes::series::{Label, SeriesLabels};
43
44use crate::histogram_eval::float_histogram::FloatHistogram;
45
46use crate::functions::Round;
47use crate::grid_series::GridSeriesBuilder;
48use crate::map_time::DateFunction;
49
50#[derive(Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
52pub enum MathOp {
53 Abs,
55 Ceil,
57 Floor,
59 Sqrt,
61 Round {
63 nearest: f64,
64 },
65 Exp,
66 Ln,
67 Log2,
68 Log10,
69 Sin,
70 Cos,
71 Tan,
72 Asin,
73 Acos,
74 Atan,
75 Sinh,
76 Cosh,
77 Tanh,
78 Asinh,
79 Acosh,
80 Atanh,
81 Deg,
82 Rad,
83 Sgn,
84 Clamp {
85 min: f64,
86 max: f64,
87 },
88 ClampMin {
89 min: f64,
90 },
91 ClampMax {
92 max: f64,
93 },
94 Date(DateFunction),
96}
97
98#[derive(Clone, Copy, Debug)]
100pub enum ArithmeticOp {
101 Add,
102 Subtract,
103 Multiply,
104 Divide,
105 Modulo,
106 Power,
107 Atan2,
108}
109
110impl std::fmt::Display for ArithmeticOp {
111 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
114 f.write_str(match self {
115 Self::Add => "+",
116 Self::Subtract => "-",
117 Self::Multiply => "*",
118 Self::Divide => "/",
119 Self::Modulo => "%",
120 Self::Power => "^",
121 Self::Atan2 => "atan2",
122 })
123 }
124}
125
126#[derive(Clone, Copy, Debug)]
128pub enum ScalarOperand {
129 Left(f64),
130 Right(f64),
131}
132
133pub fn map_math(schema: &SeriesSchema, series: &Series, op: MathOp) -> Result<Option<Series>> {
158 if op.is_empty_clamp() {
159 validate_grid_series(schema, series)?;
160 return Ok(None);
161 }
162 if !is_float_series(series) {
163 let time = validate_grid_series(schema, series)?;
164 let mut builder = GridSeriesBuilder::try_new(Arc::new(schema.clone()))?;
165 let mut cursors: Vec<_> = series.fields.iter().map(|field| field.cursor()).collect();
166 let mut row = Vec::with_capacity(cursors.len());
167 for (point, index) in time.positions() {
168 row.clear();
169 for cursor in &mut cursors {
170 row.push(
171 match cursor
172 .at(index)
173 .expect("the axis and the fields are aligned")
174 {
175 SampleRef::Float(value) => Some(op.calculate(value)),
176 SampleRef::Missing | SampleRef::Histogram(_) => None,
177 },
178 );
179 }
180 builder.push(point, &row)?;
181 }
182 return builder.finish(drop_metric_name(&series.metric)?);
183 }
184 let mut output = map_float_fields(schema, series, |floats| op.apply(floats))?;
185 output.metric = drop_metric_name(&output.metric)?;
186 Ok(Some(output))
187}
188
189pub fn map_arithmetic(
194 schema: &SeriesSchema,
195 series: &Series,
196 op: ArithmeticOp,
197 scalar: ScalarOperand,
198) -> Result<Series> {
199 let mut output = map_float_fields(schema, series, |floats| op.apply(floats, scalar))?;
200 output.metric = drop_metric_name(&output.metric)?;
201 Ok(output)
202}
203
204pub(crate) fn map_arithmetic_literal(
212 schema: &SeriesSchema,
213 series: &Series,
214 op: ArithmeticOp,
215 scalar: ScalarOperand,
216) -> Result<(Series, bool)> {
217 validate_grid_series(schema, series)?;
218 if is_float_series(series) {
219 return Ok((map_arithmetic(schema, series, op, scalar)?, false));
220 }
221
222 let mut dropped_histogram = false;
223 let fields = series
224 .fields
225 .iter()
226 .map(|samples| {
227 let segments = samples
228 .segments()
229 .iter()
230 .map(|segment| {
231 let (segment, dropped) = map_arithmetic_segment(segment, op, scalar)?;
232 dropped_histogram |= dropped;
233 Ok(segment)
234 })
235 .collect::<Result<Vec<_>>>()?;
236 Samples::try_from_chunks(segments).map_err(series_error)
237 })
238 .collect::<Result<Vec<_>>>()?;
239 let mut output = Series::try_new(
240 schema,
241 series.metric.clone(),
242 series.time.clone(),
243 SeriesFields::try_from_vec(fields).map_err(series_error)?,
244 )
245 .map_err(series_error)?;
246 output.metric = drop_metric_name(&output.metric)?;
247 Ok((output, dropped_histogram))
248}
249
250fn map_arithmetic_segment(
253 samples: &Samples,
254 op: ArithmeticOp,
255 scalar: ScalarOperand,
256) -> Result<(Samples, bool)> {
257 let mut floats = Float64Builder::with_capacity(samples.len());
258 let mut indices = UInt32Builder::with_capacity(samples.len());
259 let mut histograms = HistogramBatchBuilder::new();
260
261 let mut dropped_histogram = false;
262 for index in 0..samples.len() {
263 match samples.sample(index) {
264 SampleRef::Missing => {
265 floats.append_null();
266 indices.append_null();
267 }
268 SampleRef::Float(value) => {
269 let result = match scalar {
270 ScalarOperand::Left(left) => op.calculate(left, value),
271 ScalarOperand::Right(right) => op.calculate(value, right),
272 };
273 floats.append_value(result);
274 indices.append_null();
275 }
276 SampleRef::Histogram(view) => {
277 floats.append_null();
278 let histogram_result = match (op, scalar) {
279 (ArithmeticOp::Multiply, ScalarOperand::Left(factor))
280 | (ArithmeticOp::Multiply, ScalarOperand::Right(factor)) => {
281 let mut histogram = FloatHistogram::try_from_view(&view)?;
282 histogram.mul(factor);
283 Some(histogram)
284 }
285 (ArithmeticOp::Divide, ScalarOperand::Right(divisor)) => {
286 let mut histogram = FloatHistogram::try_from_view(&view)?;
287 histogram.div(divisor);
288 Some(histogram)
289 }
290 _ => None,
292 };
293 if let Some(mut histogram) = histogram_result {
294 histogram.compact();
295 let index = histogram.push_to(&mut histograms)?;
296 indices.append_value(index);
297 } else {
298 dropped_histogram = true;
299 indices.append_null();
300 }
301 }
302 }
303 }
304
305 let histogram_samples =
306 HistogramSamples::try_new(indices.finish(), histograms.finish().map_err(series_error)?)
307 .map_err(series_error)?;
308 let samples =
309 Samples::try_from_mixed(floats.finish(), histogram_samples).map_err(series_error)?;
310 Ok((samples, dropped_histogram))
311}
312
313pub fn constant_series(schema: &SeriesSchema, range: GridRange, scalar: f64) -> Result<Series> {
317 let fields = SeriesFields::one(Samples::from_float(Float64Array::from(vec![
318 scalar;
319 range.len()
320 ])));
321 Series::try_new(
322 schema,
323 SeriesLabels::try_new(None, vec![]).map_err(series_error)?,
324 TimeAxis::Grid(range),
325 fields,
326 )
327 .map_err(series_error)
328}
329
330pub fn map_pi(schema: &SeriesSchema, range: GridRange) -> Result<Series> {
332 constant_series(schema, range, PI)
333}
334
335fn map_float_fields(
336 schema: &SeriesSchema,
337 series: &Series,
338 map: impl Fn(&Float64Array) -> Float64Array,
339) -> Result<Series> {
340 validate_float_series(schema, series)?;
341 let fields = series
342 .fields
343 .iter()
344 .map(|samples| map_samples(samples, &map))
345 .collect::<Result<Vec<_>>>()?;
346 let fields = SeriesFields::try_from_vec(fields).map_err(series_error)?;
347 Series::try_new(schema, series.metric.clone(), series.time.clone(), fields)
348 .map_err(series_error)
349}
350
351pub(crate) fn drop_metric_name(metric: &SeriesLabels) -> Result<SeriesLabels> {
355 let tags = metric.tags();
356 let reject = |label: &Label| {
357 label.value.is_empty() || matches!(label.name.as_ref(), "__type__" | "__unit__")
358 };
359 let Some(first) = tags.iter().position(reject) else {
360 let mut result = metric.clone();
361 result.remove("__name__");
362 return Ok(result);
363 };
364
365 let mut kept = tags[..first].to_vec();
366 kept.extend(
367 tags[first + 1..]
368 .iter()
369 .filter(|label| !reject(label))
370 .cloned(),
371 );
372 SeriesLabels::try_new(None, kept).map_err(series_error)
373}
374
375pub(crate) fn drop_empty_labels(metric: &SeriesLabels) -> Result<SeriesLabels> {
377 let name = metric.name().filter(|name| !name.is_empty()).map(Arc::from);
378 rebuild_labels(metric, name, |_| true)
379}
380
381fn rebuild_labels(
383 metric: &SeriesLabels,
384 name: Option<Arc<str>>,
385 keep: impl Fn(&str) -> bool,
386) -> Result<SeriesLabels> {
387 let tags = metric
388 .tags()
389 .iter()
390 .filter(|label| !label.value.is_empty() && keep(&label.name))
391 .cloned()
392 .collect();
393 SeriesLabels::try_new(name, tags).map_err(series_error)
394}
395
396impl MathOp {
397 fn apply(self, floats: &Float64Array) -> Float64Array {
398 floats.unary(|sample| self.calculate(sample))
399 }
400
401 pub(crate) fn calculate(self, v: f64) -> f64 {
403 match self {
404 Self::Exp => v.exp(),
405 Self::Ln => v.ln(),
406 Self::Log2 => v.log2(),
407 Self::Log10 => v.log10(),
408 Self::Sin => v.sin(),
409 Self::Cos => v.cos(),
410 Self::Tan => v.tan(),
411 Self::Asin => v.asin(),
412 Self::Acos => v.acos(),
413 Self::Atan => v.atan(),
414 Self::Sinh => v.sinh(),
415 Self::Cosh => v.cosh(),
416 Self::Tanh => v.tanh(),
417 Self::Asinh => v.asinh(),
418 Self::Acosh => v.acosh(),
419 Self::Atanh => v.atanh(),
420 Self::Deg => v * 180.0 / PI,
422 Self::Rad => v * PI / 180.0,
423 Self::Sgn => {
425 if v < 0.0 {
426 -1.0
427 } else if v > 0.0 {
428 1.0
429 } else {
430 v
431 }
432 }
433 Self::Clamp { min, max } => go_max(min, go_min(max, v)),
434 Self::ClampMin { min } => go_max(min, v),
435 Self::ClampMax { max } => go_min(max, v),
436 Self::Abs => v.abs(),
437 Self::Ceil => v.ceil(),
438 Self::Floor => v.floor(),
439 Self::Sqrt => v.sqrt(),
440 Self::Round { nearest } => Round::round_to_nearest(v, nearest),
441 Self::Date(function) => function.of_seconds(v),
442 }
443 }
444
445 fn is_empty_clamp(self) -> bool {
447 match self {
448 Self::Clamp { min, max } => max < min,
449 _ => false,
450 }
451 }
452}
453
454fn go_max(x: f64, y: f64) -> f64 {
456 if x == f64::INFINITY || y == f64::INFINITY {
457 f64::INFINITY
458 } else if x.is_nan() || y.is_nan() {
459 f64::NAN
460 } else if x == 0.0 && x == y {
461 if x.is_sign_negative() { y } else { x }
462 } else if x > y {
463 x
464 } else {
465 y
466 }
467}
468
469fn go_min(x: f64, y: f64) -> f64 {
471 if x == f64::NEG_INFINITY || y == f64::NEG_INFINITY {
472 f64::NEG_INFINITY
473 } else if x.is_nan() || y.is_nan() {
474 f64::NAN
475 } else if x == 0.0 && x == y {
476 if x.is_sign_negative() { x } else { y }
477 } else if x < y {
478 x
479 } else {
480 y
481 }
482}
483
484impl ArithmeticOp {
485 #[inline]
489 pub fn calculate(self, left: f64, right: f64) -> f64 {
490 match self {
491 Self::Add => left + right,
492 Self::Subtract => left - right,
493 Self::Multiply => left * right,
494 Self::Divide => left / right,
495 Self::Modulo => left % right,
496 Self::Power => left.powf(right),
497 Self::Atan2 => left.atan2(right),
498 }
499 }
500
501 fn apply(self, floats: &Float64Array, scalar: ScalarOperand) -> Float64Array {
502 match scalar {
503 ScalarOperand::Left(scalar) => floats.unary(|sample| self.calculate(scalar, sample)),
504 ScalarOperand::Right(scalar) => floats.unary(|sample| self.calculate(sample, scalar)),
505 }
506 }
507}
508
509fn map_samples(samples: &Samples, map: &impl Fn(&Float64Array) -> Float64Array) -> Result<Samples> {
510 let chunks = samples
511 .segments()
512 .iter()
513 .map(|segment| map_float_segment(segment, map))
514 .collect::<Result<Vec<_>>>()?;
515 Samples::try_from_chunks(chunks).map_err(series_error)
516}
517
518fn map_float_segment(
519 segment: &Samples,
520 map: &impl Fn(&Float64Array) -> Float64Array,
521) -> Result<Samples> {
522 let Some(DenseSamplesRef::Float(floats)) = segment.dense() else {
523 return Err(DataFusionError::NotImplemented(
524 "Series operators support only float samples; histogram/mixed samples are not supported"
525 .into(),
526 ));
527 };
528 Ok(Samples::from_float(map(floats)))
529}
530
531fn series_error(error: datatypes::error::Error) -> DataFusionError {
532 DataFusionError::External(Box::new(error))
533}
534
535pub(crate) fn validate_float_series<'a>(
540 schema: &SeriesSchema,
541 series: &'a Series,
542) -> Result<&'a TimeAxis> {
543 let time = validate_grid_series(schema, series)?;
544 if !is_float_series(series) {
545 return Err(DataFusionError::NotImplemented(
546 "Series operators support only float samples; histogram/mixed samples are not supported"
547 .into(),
548 ));
549 }
550 Ok(time)
551}
552
553pub(crate) fn is_float_series(series: &Series) -> bool {
555 series.fields.iter().all(|field| {
556 field
557 .segments()
558 .iter()
559 .all(|segment| matches!(segment.dense(), Some(DenseSamplesRef::Float(_))))
560 })
561}
562
563pub(crate) fn validate_grid_series<'a>(
565 schema: &SeriesSchema,
566 series: &'a Series,
567) -> Result<&'a TimeAxis> {
568 let time = &series.time;
569 if time.grid().is_none() {
570 return Err(DataFusionError::Execution(
571 "Series operators require an evaluated grid time axis".into(),
572 ));
573 }
574 Series::try_new(
575 schema,
576 series.metric.clone(),
577 series.time.clone(),
578 series.fields.clone(),
579 )
580 .map_err(series_error)?;
581 Ok(time)
582}
583
584fn float_sample(sample: SampleRef<'_>) -> Option<f64> {
586 match sample {
587 SampleRef::Float(sample) => Some(sample),
588 SampleRef::Missing => None,
589 _ => unreachable!("validated as float"),
590 }
591}
592
593impl PartialEq for MathOp {
594 fn eq(&self, o: &Self) -> bool {
595 match (self, o) {
596 (Self::Round { nearest: a }, Self::Round { nearest: b }) => a.to_bits() == b.to_bits(),
597 (Self::Clamp { min: a, max: b }, Self::Clamp { min: c, max: d }) => {
598 a.to_bits() == c.to_bits() && b.to_bits() == d.to_bits()
599 }
600 (Self::ClampMin { min: a }, Self::ClampMin { min: b })
601 | (Self::ClampMax { max: a }, Self::ClampMax { max: b }) => a.to_bits() == b.to_bits(),
602 (Self::Date(a), Self::Date(b)) => a == b,
603 _ => std::mem::discriminant(self) == std::mem::discriminant(o),
604 }
605 }
606}
607impl Eq for MathOp {}
608impl std::hash::Hash for MathOp {
609 fn hash<H: std::hash::Hasher>(&self, h: &mut H) {
610 std::mem::discriminant(self).hash(h);
611 match self {
612 Self::Round { nearest: x } | Self::ClampMin { min: x } | Self::ClampMax { max: x } => {
613 x.to_bits().hash(h)
614 }
615 Self::Clamp { min, max } => {
616 min.to_bits().hash(h);
617 max.to_bits().hash(h)
618 }
619 Self::Date(d) => d.hash(h),
620 _ => (),
621 }
622 }
623}