1use std::sync::Arc;
16
17use datafusion::error::{DataFusionError, Result};
18use datatypes::series::SeriesLabels;
19use datatypes::series::samples::{FieldSpec, SampleRef, Series, SeriesSchema};
20use datatypes::series::time::TimeAxis;
21
22use crate::grid_series::GridSeriesBuilder;
23use crate::map::{
24 ArithmeticOp, Comparison, MathOp, drop_metric_name, float_sample, validate_float_series,
25 validate_grid_series,
26};
27
28#[derive(Clone, Copy, Debug)]
30pub enum ScalarSeriesOperand<'a> {
31 Left(&'a Series),
32 Right(&'a Series),
33}
34
35pub fn map_arithmetic_series(
48 schema: &Arc<SeriesSchema>,
49 vector: &Series,
50 op: ArithmeticOp,
51 scalar: ScalarSeriesOperand<'_>,
52) -> Result<Option<Series>> {
53 let metric = drop_metric_name(&vector.metric)?;
54 let (output, _) = map_grid_scalar(
55 schema,
56 vector,
57 scalar,
58 metric,
59 NonFloatSample::Impossible,
60 |left, right, _| Some(op.calculate(left, right)),
61 )?;
62 Ok(output)
63}
64
65pub fn map_compare_series(
76 schema: &Arc<SeriesSchema>,
77 vector: &Series,
78 comparison: Comparison,
79 scalar: ScalarSeriesOperand<'_>,
80) -> Result<(Option<Series>, bool)> {
81 let metric = if matches!(comparison, Comparison::Bool(_)) {
82 drop_metric_name(&vector.metric)?
83 } else {
84 vector.metric.clone()
85 };
86 map_grid_scalar(
87 schema,
88 vector,
89 scalar,
90 metric,
91 NonFloatSample::Drop,
92 |left, right, sample| comparison.apply(left, right, sample),
93 )
94}
95
96#[derive(Clone, Copy, Debug, PartialEq, Eq)]
99pub(crate) enum ScalarFunction {
100 MaxOf,
101 MinOf,
102}
103
104impl ScalarFunction {
105 pub(crate) fn apply(self, a: f64, b: f64) -> f64 {
111 let (wins, signed_zero_wins) = match self {
112 Self::MaxOf => (f64::INFINITY, false),
113 Self::MinOf => (f64::NEG_INFINITY, true),
114 };
115 if a == wins || b == wins {
116 wins
117 } else if a.is_nan() || b.is_nan() {
118 f64::NAN
119 } else if a == 0.0 && a == b {
120 if a.is_sign_negative() == signed_zero_wins {
121 a
122 } else {
123 b
124 }
125 } else if (a > b) == (self == Self::MaxOf) {
126 a
127 } else {
128 b
129 }
130 }
131}
132
133#[derive(Clone, Copy, Debug)]
140pub enum ParameterizedMath<'a> {
141 Round { to_nearest: &'a Series },
143 Clamp { min: &'a Series, max: &'a Series },
145 ClampMin { min: &'a Series },
147 ClampMax { max: &'a Series },
149 MaxOf { other: &'a Series },
152 MinOf { other: &'a Series },
155}
156
157impl<'a> ParameterizedMath<'a> {
158 fn parameters(self) -> Vec<&'a Series> {
160 match self {
161 Self::Round { to_nearest } => vec![to_nearest],
162 Self::Clamp { min, max } => vec![min, max],
163 Self::ClampMin { min } => vec![min],
164 Self::ClampMax { max } => vec![max],
165 Self::MaxOf { other } | Self::MinOf { other } => vec![other],
166 }
167 }
168
169 fn at(self, values: &[f64]) -> PointMath {
171 match self {
172 Self::Round { .. } => PointMath::Math(MathOp::Round { nearest: values[0] }),
173 Self::Clamp { .. } => PointMath::Math(MathOp::Clamp {
174 min: values[0],
175 max: values[1],
176 }),
177 Self::ClampMin { .. } => PointMath::Math(MathOp::ClampMin { min: values[0] }),
178 Self::ClampMax { .. } => PointMath::Math(MathOp::ClampMax { max: values[0] }),
179 Self::MaxOf { .. } => PointMath::Scalar {
180 function: ScalarFunction::MaxOf,
181 other: values[0],
182 },
183 Self::MinOf { .. } => PointMath::Scalar {
184 function: ScalarFunction::MinOf,
185 other: values[0],
186 },
187 }
188 }
189}
190
191#[derive(Clone, Copy, Debug)]
194enum PointMath {
195 Math(MathOp),
197 Scalar {
200 function: ScalarFunction,
201 other: f64,
202 },
203}
204
205impl PointMath {
206 fn calculate(self, value: f64) -> Option<f64> {
209 match self {
210 Self::Math(op) => (!op.is_empty_clamp()).then(|| op.calculate(value)),
211 Self::Scalar { function, other } => Some(function.apply(value, other)),
212 }
213 }
214}
215
216pub fn map_math_with_parameters(
228 schema: &Arc<SeriesSchema>,
229 series: &Series,
230 function: ParameterizedMath<'_>,
231) -> Result<Option<Series>> {
232 let time = validate_grid_series(schema, series)?;
233 let parameters = function.parameters();
234 let mut parameter_axes = Vec::with_capacity(parameters.len());
235 for parameter in ¶meters {
236 parameter_axes.push(validate_scalar(schema, parameter)?);
237 }
238 let mut parameter_cursors: Vec<_> = parameters
240 .iter()
241 .map(|parameter| parameter.fields.as_slice()[0].cursor())
242 .collect();
243 let mut field_cursors: Vec<_> = series.fields.iter().map(|field| field.cursor()).collect();
244 let mut values = Vec::with_capacity(parameters.len());
245 let mut row = Vec::with_capacity(field_cursors.len());
246 let mut builder = GridSeriesBuilder::try_new(schema.clone())?;
247 for (point, index) in time.positions() {
248 values.clear();
249 for (axis, cursor) in parameter_axes.iter().zip(&mut parameter_cursors) {
250 let value = axis.row_of(point).and_then(|row| {
251 float_sample(cursor.at(row).expect("parameter rows only increase"))
252 });
253 values.extend(value);
254 }
255 let op = (values.len() == parameters.len()).then(|| function.at(&values));
256 row.clear();
257 for cursor in &mut field_cursors {
258 let sample = cursor
259 .at(index)
260 .expect("the axis and the fields are aligned");
261 row.push(match (op, sample) {
262 (Some(op), SampleRef::Float(value)) => op.calculate(value),
263 _ => None,
264 });
265 }
266 builder.push(point, &row)?;
267 }
268 builder.finish(drop_metric_name(&series.metric)?)
269}
270
271#[derive(Clone, Copy, Debug)]
274enum NonFloatSample {
275 Impossible,
277 Drop,
281}
282
283fn map_grid_scalar(
284 schema: &Arc<SeriesSchema>,
285 vector: &Series,
286 scalar: ScalarSeriesOperand<'_>,
287 metric: SeriesLabels,
288 non_float: NonFloatSample,
289 calculate: impl Fn(f64, f64, f64) -> Option<f64>,
290) -> Result<(Option<Series>, bool)> {
291 let vector_time = match non_float {
292 NonFloatSample::Impossible => validate_float_series(schema, vector)?,
293 NonFloatSample::Drop => validate_grid_series(schema, vector)?,
294 };
295 let (scalar_series, scalar_left) = match scalar {
296 ScalarSeriesOperand::Left(s) => (s, true),
297 ScalarSeriesOperand::Right(s) => (s, false),
298 };
299 let scalar_time = validate_scalar(schema, scalar_series)?;
300 let mut builder = GridSeriesBuilder::try_new(schema.clone())?;
301 let mut scalar_samples = scalar_series.fields.as_slice()[0].cursor();
305 let mut field_samples = vector
306 .fields
307 .iter()
308 .map(|field| field.cursor())
309 .collect::<Vec<_>>();
310 let mut row = Vec::with_capacity(field_samples.len());
311 let mut dropped_histogram = false;
312 for pair in vector_time.intersect_runs(scalar_time) {
313 for offset in 0..pair.len {
314 let scalar = float_sample(
315 scalar_samples
316 .at(pair.other_row + offset)
317 .expect("the shared run lies inside the scalar axis"),
318 );
319 row.clear();
320 for field in &mut field_samples {
321 let sample = match field
322 .at(pair.row + offset)
323 .expect("the shared run lies inside the vector axis")
324 {
325 SampleRef::Float(value) => Some(value),
326 SampleRef::Missing => None,
327 SampleRef::Histogram(_) => {
328 match non_float {
329 NonFloatSample::Drop => dropped_histogram = true,
330 NonFloatSample::Impossible => {
331 unreachable!("validated as float")
332 }
333 }
334 None
335 }
336 };
337 row.push(scalar.zip(sample).and_then(|(scalar, sample)| {
338 if scalar_left {
339 calculate(scalar, sample, sample)
340 } else {
341 calculate(sample, scalar, sample)
342 }
343 }));
344 }
345 builder.push(pair.position + offset, &row)?;
346 }
347 }
348 Ok((builder.finish(metric)?, dropped_histogram))
349}
350
351pub(crate) fn validate_scalar<'a>(
352 schema: &SeriesSchema,
353 scalar: &'a Series,
354) -> Result<&'a TimeAxis> {
355 if scalar.metric.name().is_some() || !scalar.metric.tags().is_empty() {
356 return Err(DataFusionError::Execution(
357 "grid scalar must be unlabelled".into(),
358 ));
359 }
360 let schema = SeriesSchema {
361 fields: vec![FieldSpec {
362 name: "scalar".into(),
363 }]
364 .into(),
365 eval_grid: schema.eval_grid.clone(),
366 };
367 validate_float_series(&schema, scalar)
368}