Skip to main content

datafusion_expr_common/
statistics.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Probabilistic distributions for expression-level statistics (unused).
6//!
7//! Note: All public items in this module are **deprecated** as of `54.0.0`.
8//!
9//! See <https://github.com/apache/datafusion/pull/22071> for details.
10
11// The whole module is deprecated; suppress warnings from intra-module uses
12// of the deprecated types so the module continues to compile.
13#![allow(deprecated)]
14
15use std::f64::consts::LN_2;
16
17use crate::interval_arithmetic::{Interval, apply_operator};
18use crate::operator::Operator;
19use crate::type_coercion::binary::binary_numeric_coercion;
20
21use arrow::array::ArrowNativeTypeOp;
22use arrow::datatypes::DataType;
23use datafusion_common::rounding::alter_fp_rounding_mode;
24use datafusion_common::{
25    Result, ScalarValue, assert_eq_or_internal_err, assert_ne_or_internal_err,
26    assert_or_internal_err, internal_err, not_impl_err,
27};
28
29/// This object defines probabilistic distributions that encode uncertain
30/// information about a single, scalar value. Currently, we support five core
31/// statistical distributions. New variants will be added over time.
32///
33/// This object is the lowest-level object in the statistics hierarchy, and it
34/// is the main unit of calculus when evaluating expressions in a statistical
35/// context. Notions like column and table statistics are built on top of this
36/// object and the operations it supports.
37#[deprecated(
38    since = "54.0.0",
39    note = "Part of the unused Statistics V2 framework; see https://github.com/apache/datafusion/pull/22071"
40)]
41#[derive(Clone, Debug, PartialEq)]
42pub enum Distribution {
43    Uniform(UniformDistribution),
44    Exponential(ExponentialDistribution),
45    Gaussian(GaussianDistribution),
46    Bernoulli(BernoulliDistribution),
47    Generic(GenericDistribution),
48}
49
50use Distribution::{Bernoulli, Exponential, Gaussian, Generic, Uniform};
51
52impl Distribution {
53    /// Constructs a new [`Uniform`] distribution from the given [`Interval`].
54    pub fn new_uniform(interval: Interval) -> Result<Self> {
55        UniformDistribution::try_new(interval).map(Uniform)
56    }
57
58    /// Constructs a new [`Exponential`] distribution from the given rate/offset
59    /// pair, and validates the given parameters.
60    pub fn new_exponential(
61        rate: ScalarValue,
62        offset: ScalarValue,
63        positive_tail: bool,
64    ) -> Result<Self> {
65        ExponentialDistribution::try_new(rate, offset, positive_tail).map(Exponential)
66    }
67
68    /// Constructs a new [`Gaussian`] distribution from the given mean/variance
69    /// pair, and validates the given parameters.
70    pub fn new_gaussian(mean: ScalarValue, variance: ScalarValue) -> Result<Self> {
71        GaussianDistribution::try_new(mean, variance).map(Gaussian)
72    }
73
74    /// Constructs a new [`Bernoulli`] distribution from the given success
75    /// probability, and validates the given parameters.
76    pub fn new_bernoulli(p: ScalarValue) -> Result<Self> {
77        BernoulliDistribution::try_new(p).map(Bernoulli)
78    }
79
80    /// Constructs a new [`Generic`] distribution from the given mean, median,
81    /// variance, and range values after validating the given parameters.
82    pub fn new_generic(
83        mean: ScalarValue,
84        median: ScalarValue,
85        variance: ScalarValue,
86        range: Interval,
87    ) -> Result<Self> {
88        GenericDistribution::try_new(mean, median, variance, range).map(Generic)
89    }
90
91    /// Constructs a new [`Generic`] distribution from the given range. Other
92    /// parameters (mean, median and variance) are initialized with null values.
93    pub fn new_from_interval(range: Interval) -> Result<Self> {
94        let null = ScalarValue::try_from(range.data_type())?;
95        Distribution::new_generic(null.clone(), null.clone(), null, range)
96    }
97
98    /// Extracts the mean value of this uncertain quantity, depending on its
99    /// distribution:
100    /// - A [`Uniform`] distribution's interval determines its mean value, which
101    ///   is the arithmetic average of the interval endpoints.
102    /// - An [`Exponential`] distribution's mean is calculable by the formula
103    ///   `offset + 1 / λ`, where `λ` is the (non-negative) rate.
104    /// - A [`Gaussian`] distribution contains the mean explicitly.
105    /// - A [`Bernoulli`] distribution's mean is equal to its success probability `p`.
106    /// - A [`Generic`] distribution _may_ have it explicitly, or this information
107    ///   may be absent.
108    pub fn mean(&self) -> Result<ScalarValue> {
109        match &self {
110            Uniform(u) => u.mean(),
111            Exponential(e) => e.mean(),
112            Gaussian(g) => Ok(g.mean().clone()),
113            Bernoulli(b) => Ok(b.mean().clone()),
114            Generic(u) => Ok(u.mean().clone()),
115        }
116    }
117
118    /// Extracts the median value of this uncertain quantity, depending on its
119    /// distribution:
120    /// - A [`Uniform`] distribution's interval determines its median value, which
121    ///   is the arithmetic average of the interval endpoints.
122    /// - An [`Exponential`] distribution's median is calculable by the formula
123    ///   `offset + ln(2) / λ`, where `λ` is the (non-negative) rate.
124    /// - A [`Gaussian`] distribution's median is equal to its mean, which is
125    ///   specified explicitly.
126    /// - A [`Bernoulli`] distribution's median is `1` if `p > 0.5` and `0`
127    ///   otherwise, where `p` is the success probability.
128    /// - A [`Generic`] distribution _may_ have it explicitly, or this information
129    ///   may be absent.
130    pub fn median(&self) -> Result<ScalarValue> {
131        match &self {
132            Uniform(u) => u.median(),
133            Exponential(e) => e.median(),
134            Gaussian(g) => Ok(g.median().clone()),
135            Bernoulli(b) => b.median(),
136            Generic(u) => Ok(u.median().clone()),
137        }
138    }
139
140    /// Extracts the variance value of this uncertain quantity, depending on
141    /// its distribution:
142    /// - A [`Uniform`] distribution's interval determines its variance value, which
143    ///   is calculable by the formula `(upper - lower) ^ 2 / 12`.
144    /// - An [`Exponential`] distribution's variance is calculable by the formula
145    ///   `1 / (λ ^ 2)`, where `λ` is the (non-negative) rate.
146    /// - A [`Gaussian`] distribution's variance is specified explicitly.
147    /// - A [`Bernoulli`] distribution's median is given by the formula `p * (1 - p)`
148    ///   where `p` is the success probability.
149    /// - A [`Generic`] distribution _may_ have it explicitly, or this information
150    ///   may be absent.
151    pub fn variance(&self) -> Result<ScalarValue> {
152        match &self {
153            Uniform(u) => u.variance(),
154            Exponential(e) => e.variance(),
155            Gaussian(g) => Ok(g.variance.clone()),
156            Bernoulli(b) => b.variance(),
157            Generic(u) => Ok(u.variance.clone()),
158        }
159    }
160
161    /// Extracts the range of this uncertain quantity, depending on its
162    /// distribution:
163    /// - A [`Uniform`] distribution's range is simply its interval.
164    /// - An [`Exponential`] distribution's range is `[offset, +∞)`.
165    /// - A [`Gaussian`] distribution's range is unbounded.
166    /// - A [`Bernoulli`] distribution's range is [`Interval::TRUE_OR_FALSE`], if
167    ///   `p` is neither `0` nor `1`. Otherwise, it is [`Interval::FALSE`]
168    ///   and [`Interval::TRUE`], respectively.
169    /// - A [`Generic`] distribution is unbounded by default, but more information
170    ///   may be present.
171    pub fn range(&self) -> Result<Interval> {
172        match &self {
173            Uniform(u) => Ok(u.range().clone()),
174            Exponential(e) => e.range(),
175            Gaussian(g) => g.range(),
176            Bernoulli(b) => Ok(b.range()),
177            Generic(u) => Ok(u.range().clone()),
178        }
179    }
180
181    /// Returns the data type of the statistical parameters comprising this
182    /// distribution.
183    pub fn data_type(&self) -> DataType {
184        match &self {
185            Uniform(u) => u.data_type(),
186            Exponential(e) => e.data_type(),
187            Gaussian(g) => g.data_type(),
188            Bernoulli(b) => b.data_type(),
189            Generic(u) => u.data_type(),
190        }
191    }
192
193    pub fn target_type(args: &[&ScalarValue]) -> Result<DataType> {
194        let mut arg_types = args
195            .iter()
196            .filter(|&&arg| arg != &ScalarValue::Null)
197            .map(|&arg| arg.data_type());
198
199        let Some(dt) = arg_types.next().map_or_else(
200            || Some(DataType::Null),
201            |first| {
202                arg_types
203                    .try_fold(first, |target, arg| binary_numeric_coercion(&target, &arg))
204            },
205        ) else {
206            return internal_err!("Can only evaluate statistics for numeric types");
207        };
208        Ok(dt)
209    }
210}
211
212/// Uniform distribution, represented by its range. If the given range extends
213/// towards infinity, the distribution will be improper -- which is OK. For a
214/// more in-depth discussion, see:
215///
216/// <https://en.wikipedia.org/wiki/Continuous_uniform_distribution>
217/// <https://en.wikipedia.org/wiki/Prior_probability#Improper_priors>
218#[deprecated(
219    since = "54.0.0",
220    note = "Part of the unused Statistics V2 framework; see https://github.com/apache/datafusion/pull/22071"
221)]
222#[derive(Clone, Debug, PartialEq)]
223pub struct UniformDistribution {
224    interval: Interval,
225}
226
227/// Exponential distribution with an optional shift. The probability density
228/// function (PDF) is defined as follows:
229///
230/// For a positive tail (when `positive_tail` is `true`):
231///
232/// `f(x; λ, offset) = λ exp(-λ (x - offset))    for x ≥ offset`
233///
234/// For a negative tail (when `positive_tail` is `false`):
235///
236/// `f(x; λ, offset) = λ exp(-λ (offset - x))    for x ≤ offset`
237///
238///
239/// In both cases, the PDF is `0` outside the specified domain.
240///
241/// For more information, see:
242///
243/// <https://en.wikipedia.org/wiki/Exponential_distribution>
244#[deprecated(
245    since = "54.0.0",
246    note = "Part of the unused Statistics V2 framework; see https://github.com/apache/datafusion/pull/22071"
247)]
248#[derive(Clone, Debug, PartialEq)]
249pub struct ExponentialDistribution {
250    rate: ScalarValue,
251    offset: ScalarValue,
252    /// Indicates whether the exponential distribution has a positive tail;
253    /// i.e. it extends towards positive infinity.
254    positive_tail: bool,
255}
256
257/// Gaussian (normal) distribution, represented by its mean and variance.
258/// For a more in-depth discussion, see:
259///
260/// <https://en.wikipedia.org/wiki/Normal_distribution>
261#[deprecated(
262    since = "54.0.0",
263    note = "Part of the unused Statistics V2 framework; see https://github.com/apache/datafusion/pull/22071"
264)]
265#[derive(Clone, Debug, PartialEq)]
266pub struct GaussianDistribution {
267    mean: ScalarValue,
268    variance: ScalarValue,
269}
270
271/// Bernoulli distribution with success probability `p`. If `p` has a null value,
272/// the success probability is unknown. For a more in-depth discussion, see:
273///
274/// <https://en.wikipedia.org/wiki/Bernoulli_distribution>
275#[deprecated(
276    since = "54.0.0",
277    note = "Part of the unused Statistics V2 framework; see https://github.com/apache/datafusion/pull/22071"
278)]
279#[derive(Clone, Debug, PartialEq)]
280pub struct BernoulliDistribution {
281    p: ScalarValue,
282}
283
284/// A generic distribution whose functional form is not available, which is
285/// approximated via some summary statistics. For a more in-depth discussion, see:
286///
287/// <https://en.wikipedia.org/wiki/Summary_statistics>
288#[deprecated(
289    since = "54.0.0",
290    note = "Part of the unused Statistics V2 framework; see https://github.com/apache/datafusion/pull/22071"
291)]
292#[derive(Clone, Debug, PartialEq)]
293pub struct GenericDistribution {
294    mean: ScalarValue,
295    median: ScalarValue,
296    variance: ScalarValue,
297    range: Interval,
298}
299
300impl UniformDistribution {
301    fn try_new(interval: Interval) -> Result<Self> {
302        assert_ne_or_internal_err!(
303            interval.data_type(),
304            DataType::Boolean,
305            "Construction of a boolean `Uniform` distribution is prohibited, create a `Bernoulli` distribution instead."
306        );
307
308        Ok(Self { interval })
309    }
310
311    pub fn data_type(&self) -> DataType {
312        self.interval.data_type()
313    }
314
315    /// Computes the mean value of this distribution. In case of improper
316    /// distributions (i.e. when the range is unbounded), the function returns
317    /// a `NULL` `ScalarValue`.
318    pub fn mean(&self) -> Result<ScalarValue> {
319        // TODO: Should we ensure that this always returns a real number data type?
320        let dt = self.data_type();
321        let two = ScalarValue::from(2).cast_to(&dt)?;
322        let result = self
323            .interval
324            .lower()
325            .add_checked(self.interval.upper())?
326            .div(two);
327        debug_assert!(
328            !self.interval.is_unbounded() || result.as_ref().is_ok_and(|r| r.is_null())
329        );
330        result
331    }
332
333    pub fn median(&self) -> Result<ScalarValue> {
334        self.mean()
335    }
336
337    /// Computes the variance value of this distribution. In case of improper
338    /// distributions (i.e. when the range is unbounded), the function returns
339    /// a `NULL` `ScalarValue`.
340    pub fn variance(&self) -> Result<ScalarValue> {
341        // TODO: Should we ensure that this always returns a real number data type?
342        let width = self.interval.width()?;
343        let dt = width.data_type();
344        let twelve = ScalarValue::from(12).cast_to(&dt)?;
345        let result = width.mul_checked(&width)?.div(twelve);
346        debug_assert!(
347            !self.interval.is_unbounded() || result.as_ref().is_ok_and(|r| r.is_null())
348        );
349        result
350    }
351
352    pub fn range(&self) -> &Interval {
353        &self.interval
354    }
355}
356
357impl ExponentialDistribution {
358    fn try_new(
359        rate: ScalarValue,
360        offset: ScalarValue,
361        positive_tail: bool,
362    ) -> Result<Self> {
363        let dt = rate.data_type();
364        assert_eq_or_internal_err!(
365            offset.data_type(),
366            dt,
367            "Rate and offset must have the same data type"
368        );
369        assert_or_internal_err!(
370            !offset.is_null(),
371            "Offset of an `ExponentialDistribution` cannot be null"
372        );
373        assert_or_internal_err!(
374            !rate.is_null(),
375            "Rate of an `ExponentialDistribution` cannot be null"
376        );
377        let zero = ScalarValue::new_zero(&dt)?;
378        assert_or_internal_err!(
379            !rate.le(&zero),
380            "Rate of an `ExponentialDistribution` must be positive"
381        );
382        Ok(Self {
383            rate,
384            offset,
385            positive_tail,
386        })
387    }
388
389    pub fn data_type(&self) -> DataType {
390        self.rate.data_type()
391    }
392
393    pub fn rate(&self) -> &ScalarValue {
394        &self.rate
395    }
396
397    pub fn offset(&self) -> &ScalarValue {
398        &self.offset
399    }
400
401    pub fn positive_tail(&self) -> bool {
402        self.positive_tail
403    }
404
405    pub fn mean(&self) -> Result<ScalarValue> {
406        // TODO: Should we ensure that this always returns a real number data type?
407        let one = ScalarValue::new_one(&self.data_type())?;
408        let tail_mean = one.div(&self.rate)?;
409        if self.positive_tail {
410            self.offset.add_checked(tail_mean)
411        } else {
412            self.offset.sub_checked(tail_mean)
413        }
414    }
415
416    pub fn median(&self) -> Result<ScalarValue> {
417        // TODO: Should we ensure that this always returns a real number data type?
418        let ln_two = ScalarValue::from(LN_2).cast_to(&self.data_type())?;
419        let tail_median = ln_two.div(&self.rate)?;
420        if self.positive_tail {
421            self.offset.add_checked(tail_median)
422        } else {
423            self.offset.sub_checked(tail_median)
424        }
425    }
426
427    pub fn variance(&self) -> Result<ScalarValue> {
428        // TODO: Should we ensure that this always returns a real number data type?
429        let one = ScalarValue::new_one(&self.data_type())?;
430        let rate_squared = self.rate.mul_checked(&self.rate)?;
431        one.div(rate_squared)
432    }
433
434    pub fn range(&self) -> Result<Interval> {
435        let end = ScalarValue::try_from(&self.data_type())?;
436        if self.positive_tail {
437            Interval::try_new(self.offset.clone(), end)
438        } else {
439            Interval::try_new(end, self.offset.clone())
440        }
441    }
442}
443
444impl GaussianDistribution {
445    fn try_new(mean: ScalarValue, variance: ScalarValue) -> Result<Self> {
446        let dt = mean.data_type();
447        assert_eq_or_internal_err!(
448            variance.data_type(),
449            dt,
450            "Mean and variance must have the same data type"
451        );
452        assert_or_internal_err!(
453            !variance.is_null(),
454            "Variance of a `GaussianDistribution` cannot be null"
455        );
456        let zero = ScalarValue::new_zero(&dt)?;
457        assert_or_internal_err!(
458            !variance.lt(&zero),
459            "Variance of a `GaussianDistribution` must be positive"
460        );
461        Ok(Self { mean, variance })
462    }
463
464    pub fn data_type(&self) -> DataType {
465        self.mean.data_type()
466    }
467
468    pub fn mean(&self) -> &ScalarValue {
469        &self.mean
470    }
471
472    pub fn variance(&self) -> &ScalarValue {
473        &self.variance
474    }
475
476    pub fn median(&self) -> &ScalarValue {
477        self.mean()
478    }
479
480    pub fn range(&self) -> Result<Interval> {
481        Interval::make_unbounded(&self.data_type())
482    }
483}
484
485impl BernoulliDistribution {
486    fn try_new(p: ScalarValue) -> Result<Self> {
487        if p.is_null() {
488            return Ok(Self { p });
489        }
490        let dt = p.data_type();
491        let zero = ScalarValue::new_zero(&dt)?;
492        let one = ScalarValue::new_one(&dt)?;
493        assert_or_internal_err!(
494            p.ge(&zero) && p.le(&one),
495            "Success probability of a `BernoulliDistribution` must be in [0, 1]"
496        );
497        Ok(Self { p })
498    }
499
500    pub fn data_type(&self) -> DataType {
501        self.p.data_type()
502    }
503
504    pub fn p_value(&self) -> &ScalarValue {
505        &self.p
506    }
507
508    pub fn mean(&self) -> &ScalarValue {
509        &self.p
510    }
511
512    /// Computes the median value of this distribution. In case of an unknown
513    /// success probability, the function returns a `NULL` `ScalarValue`.
514    pub fn median(&self) -> Result<ScalarValue> {
515        let dt = self.data_type();
516        if self.p.is_null() {
517            ScalarValue::try_from(&dt)
518        } else {
519            let one = ScalarValue::new_one(&dt)?;
520            if one.sub_checked(&self.p)?.lt(&self.p) {
521                ScalarValue::new_one(&dt)
522            } else {
523                ScalarValue::new_zero(&dt)
524            }
525        }
526    }
527
528    /// Computes the variance value of this distribution. In case of an unknown
529    /// success probability, the function returns a `NULL` `ScalarValue`.
530    pub fn variance(&self) -> Result<ScalarValue> {
531        let dt = self.data_type();
532        let one = ScalarValue::new_one(&dt)?;
533        let result = one.sub_checked(&self.p)?.mul_checked(&self.p);
534        debug_assert!(!self.p.is_null() || result.as_ref().is_ok_and(|r| r.is_null()));
535        result
536    }
537
538    pub fn range(&self) -> Interval {
539        let dt = self.data_type();
540        // Unwraps are safe as the constructor guarantees that the data type
541        // supports zero and one values.
542        if ScalarValue::new_zero(&dt).unwrap().eq(&self.p) {
543            Interval::FALSE
544        } else if ScalarValue::new_one(&dt).unwrap().eq(&self.p) {
545            Interval::TRUE
546        } else {
547            Interval::TRUE_OR_FALSE
548        }
549    }
550}
551
552impl GenericDistribution {
553    fn try_new(
554        mean: ScalarValue,
555        median: ScalarValue,
556        variance: ScalarValue,
557        range: Interval,
558    ) -> Result<Self> {
559        assert_ne_or_internal_err!(
560            range.data_type(),
561            DataType::Boolean,
562            "Construction of a boolean `Generic` distribution is prohibited, create a `Bernoulli` distribution instead."
563        );
564
565        let validate_location = |m: &ScalarValue| -> Result<bool> {
566            // Checks whether the given location estimate is within the range.
567            if m.is_null() {
568                Ok(true)
569            } else {
570                range.contains_value(m)
571            }
572        };
573
574        let locations_valid = validate_location(&mean)? && validate_location(&median)?;
575        let variance_non_negative = if variance.is_null() {
576            true
577        } else {
578            let zero = ScalarValue::new_zero(&variance.data_type())?;
579            !variance.lt(&zero)
580        };
581        assert_or_internal_err!(
582            locations_valid && variance_non_negative,
583            "Tried to construct an invalid `GenericDistribution` instance"
584        );
585
586        Ok(Self {
587            mean,
588            median,
589            variance,
590            range,
591        })
592    }
593
594    pub fn data_type(&self) -> DataType {
595        self.mean.data_type()
596    }
597
598    pub fn mean(&self) -> &ScalarValue {
599        &self.mean
600    }
601
602    pub fn median(&self) -> &ScalarValue {
603        &self.median
604    }
605
606    pub fn variance(&self) -> &ScalarValue {
607        &self.variance
608    }
609
610    pub fn range(&self) -> &Interval {
611        &self.range
612    }
613}
614
615/// This function takes a logical operator and two Bernoulli distributions,
616/// and it returns a new Bernoulli distribution that represents the result of
617/// the operation. Currently, only `AND` and `OR` operations are supported.
618#[deprecated(
619    since = "54.0.0",
620    note = "Part of the unused Statistics V2 framework; see https://github.com/apache/datafusion/pull/22071"
621)]
622pub fn combine_bernoullis(
623    op: &Operator,
624    left: &BernoulliDistribution,
625    right: &BernoulliDistribution,
626) -> Result<BernoulliDistribution> {
627    let left_p = left.p_value();
628    let right_p = right.p_value();
629    match op {
630        Operator::And => match (left_p.is_null(), right_p.is_null()) {
631            (false, false) => {
632                BernoulliDistribution::try_new(left_p.mul_checked(right_p)?)
633            }
634            (false, true) if left_p.eq(&ScalarValue::new_zero(&left_p.data_type())?) => {
635                Ok(left.clone())
636            }
637            (true, false)
638                if right_p.eq(&ScalarValue::new_zero(&right_p.data_type())?) =>
639            {
640                Ok(right.clone())
641            }
642            _ => {
643                let dt = Distribution::target_type(&[left_p, right_p])?;
644                BernoulliDistribution::try_new(ScalarValue::try_from(&dt)?)
645            }
646        },
647        Operator::Or => match (left_p.is_null(), right_p.is_null()) {
648            (false, false) => {
649                let sum = left_p.add_checked(right_p)?;
650                let product = left_p.mul_checked(right_p)?;
651                let or_success = sum.sub_checked(product)?;
652                BernoulliDistribution::try_new(or_success)
653            }
654            (false, true) if left_p.eq(&ScalarValue::new_one(&left_p.data_type())?) => {
655                Ok(left.clone())
656            }
657            (true, false) if right_p.eq(&ScalarValue::new_one(&right_p.data_type())?) => {
658                Ok(right.clone())
659            }
660            _ => {
661                let dt = Distribution::target_type(&[left_p, right_p])?;
662                BernoulliDistribution::try_new(ScalarValue::try_from(&dt)?)
663            }
664        },
665        _ => {
666            not_impl_err!("Statistical evaluation only supports AND and OR operators")
667        }
668    }
669}
670
671/// Applies the given operation to the given Gaussian distributions. Currently,
672/// this function handles only addition and subtraction operations. If the
673/// result is not a Gaussian random variable, it returns `None`. For details,
674/// see:
675///
676/// <https://en.wikipedia.org/wiki/Sum_of_normally_distributed_random_variables>
677#[deprecated(
678    since = "54.0.0",
679    note = "Part of the unused Statistics V2 framework; see https://github.com/apache/datafusion/pull/22071"
680)]
681pub fn combine_gaussians(
682    op: &Operator,
683    left: &GaussianDistribution,
684    right: &GaussianDistribution,
685) -> Result<Option<GaussianDistribution>> {
686    match op {
687        Operator::Plus => GaussianDistribution::try_new(
688            left.mean().add_checked(right.mean())?,
689            left.variance().add_checked(right.variance())?,
690        )
691        .map(Some),
692        Operator::Minus => GaussianDistribution::try_new(
693            left.mean().sub_checked(right.mean())?,
694            left.variance().add_checked(right.variance())?,
695        )
696        .map(Some),
697        _ => Ok(None),
698    }
699}
700
701/// Creates a new `Bernoulli` distribution by computing the resulting probability.
702/// Expects `op` to be a comparison operator, with `left` and `right` having
703/// numeric distributions. The resulting distribution has the `Float64` data
704/// type.
705#[deprecated(
706    since = "54.0.0",
707    note = "Part of the unused Statistics V2 framework; see https://github.com/apache/datafusion/pull/22071"
708)]
709pub fn create_bernoulli_from_comparison(
710    op: &Operator,
711    left: &Distribution,
712    right: &Distribution,
713) -> Result<Distribution> {
714    match (left, right) {
715        (Uniform(left), Uniform(right)) => {
716            match op {
717                Operator::Eq | Operator::NotEq => {
718                    let (li, ri) = (left.range(), right.range());
719                    if let Some(intersection) = li.intersect(ri)? {
720                        // If the ranges are not disjoint, calculate the probability
721                        // of equality using cardinalities:
722                        if let (Some(lc), Some(rc), Some(ic)) = (
723                            li.cardinality(),
724                            ri.cardinality(),
725                            intersection.cardinality(),
726                        ) {
727                            // Avoid overflow by widening the type temporarily:
728                            let pairs = ((lc as u128) * (rc as u128)) as f64;
729                            let p = (ic as f64).div_checked(pairs)?;
730                            // Alternative approach that may be more stable:
731                            // let p = (ic as f64)
732                            //     .div_checked(lc as f64)?
733                            //     .div_checked(rc as f64)?;
734
735                            let mut p_value = ScalarValue::from(p);
736                            if op == &Operator::NotEq {
737                                let one = ScalarValue::from(1.0);
738                                p_value = alter_fp_rounding_mode::<false, _>(
739                                    &one,
740                                    &p_value,
741                                    |lhs, rhs| lhs.sub_checked(rhs),
742                                )?;
743                            }
744                            return Distribution::new_bernoulli(p_value);
745                        }
746                    } else if op == &Operator::Eq {
747                        // If the ranges are disjoint, probability of equality is 0.
748                        return Distribution::new_bernoulli(ScalarValue::from(0.0));
749                    } else {
750                        // If the ranges are disjoint, probability of not-equality is 1.
751                        return Distribution::new_bernoulli(ScalarValue::from(1.0));
752                    }
753                }
754                Operator::Lt | Operator::LtEq | Operator::Gt | Operator::GtEq => {
755                    // TODO: We can handle inequality operators and calculate a
756                    // `p` value instead of falling back to an unknown Bernoulli
757                    // distribution. Note that the strict and non-strict inequalities
758                    // may require slightly different logic in case of real vs.
759                    // integral data types.
760                }
761                _ => {}
762            }
763        }
764        (Gaussian(_), Gaussian(_)) => {
765            // TODO: We can handle Gaussian comparisons and calculate a `p` value
766            //       instead of falling back to an unknown Bernoulli distribution.
767        }
768        _ => {}
769    }
770    let (li, ri) = (left.range()?, right.range()?);
771    let range_evaluation = apply_operator(op, &li, &ri)?;
772    if range_evaluation.eq(&Interval::FALSE) {
773        Distribution::new_bernoulli(ScalarValue::from(0.0))
774    } else if range_evaluation.eq(&Interval::TRUE) {
775        Distribution::new_bernoulli(ScalarValue::from(1.0))
776    } else if range_evaluation.eq(&Interval::TRUE_OR_FALSE) {
777        Distribution::new_bernoulli(ScalarValue::try_from(&DataType::Float64)?)
778    } else {
779        internal_err!("This function must be called with a comparison operator")
780    }
781}
782
783/// Creates a new [`Generic`] distribution that represents the result of the
784/// given binary operation on two unknown quantities represented by their
785/// [`Distribution`] objects. The function computes the mean, median and
786/// variance if possible.
787#[deprecated(
788    since = "54.0.0",
789    note = "Part of the unused Statistics V2 framework; see https://github.com/apache/datafusion/pull/22071"
790)]
791pub fn new_generic_from_binary_op(
792    op: &Operator,
793    left: &Distribution,
794    right: &Distribution,
795) -> Result<Distribution> {
796    Distribution::new_generic(
797        compute_mean(op, left, right)?,
798        compute_median(op, left, right)?,
799        compute_variance(op, left, right)?,
800        apply_operator(op, &left.range()?, &right.range()?)?,
801    )
802}
803
804/// Computes the mean value for the result of the given binary operation on
805/// two unknown quantities represented by their [`Distribution`] objects.
806#[deprecated(
807    since = "54.0.0",
808    note = "Part of the unused Statistics V2 framework; see https://github.com/apache/datafusion/pull/22071"
809)]
810pub fn compute_mean(
811    op: &Operator,
812    left: &Distribution,
813    right: &Distribution,
814) -> Result<ScalarValue> {
815    let (left_mean, right_mean) = (left.mean()?, right.mean()?);
816
817    match op {
818        Operator::Plus => return left_mean.add_checked(right_mean),
819        Operator::Minus => return left_mean.sub_checked(right_mean),
820        // Note the independence assumption below:
821        Operator::Multiply => return left_mean.mul_checked(right_mean),
822        // TODO: We can calculate the mean for division when we support reciprocals,
823        // or know the distributions of the operands. For details, see:
824        //
825        // <https://en.wikipedia.org/wiki/Algebra_of_random_variables>
826        // <https://stats.stackexchange.com/questions/185683/distribution-of-ratio-between-two-independent-uniform-random-variables>
827        //
828        // Fall back to an unknown mean value for division:
829        Operator::Divide => {}
830        // Fall back to an unknown mean value for other cases:
831        _ => {}
832    }
833    let target_type = Distribution::target_type(&[&left_mean, &right_mean])?;
834    ScalarValue::try_from(target_type)
835}
836
837/// Computes the median value for the result of the given binary operation on
838/// two unknown quantities represented by its [`Distribution`] objects. Currently,
839/// the median is calculable only for addition and subtraction operations on:
840/// - [`Uniform`] and [`Uniform`] distributions, and
841/// - [`Gaussian`] and [`Gaussian`] distributions.
842#[deprecated(
843    since = "54.0.0",
844    note = "Part of the unused Statistics V2 framework; see https://github.com/apache/datafusion/pull/22071"
845)]
846pub fn compute_median(
847    op: &Operator,
848    left: &Distribution,
849    right: &Distribution,
850) -> Result<ScalarValue> {
851    match (left, right) {
852        (Uniform(lu), Uniform(ru)) => {
853            let (left_median, right_median) = (lu.median()?, ru.median()?);
854            // Under the independence assumption, the result is a symmetric
855            // triangular distribution, so we can simply add/subtract the
856            // median values:
857            match op {
858                Operator::Plus => return left_median.add_checked(right_median),
859                Operator::Minus => return left_median.sub_checked(right_median),
860                // Fall back to an unknown median value for other cases:
861                _ => {}
862            }
863        }
864        // Under the independence assumption, the result is another Gaussian
865        // distribution, so we can simply add/subtract the median values:
866        (Gaussian(lg), Gaussian(rg)) => match op {
867            Operator::Plus => return lg.mean().add_checked(rg.mean()),
868            Operator::Minus => return lg.mean().sub_checked(rg.mean()),
869            // Fall back to an unknown median value for other cases:
870            _ => {}
871        },
872        // Fall back to an unknown median value for other cases:
873        _ => {}
874    }
875
876    let (left_median, right_median) = (left.median()?, right.median()?);
877    let target_type = Distribution::target_type(&[&left_median, &right_median])?;
878    ScalarValue::try_from(target_type)
879}
880
881/// Computes the variance value for the result of the given binary operation on
882/// two unknown quantities represented by their [`Distribution`] objects.
883#[deprecated(
884    since = "54.0.0",
885    note = "Part of the unused Statistics V2 framework; see https://github.com/apache/datafusion/pull/22071"
886)]
887pub fn compute_variance(
888    op: &Operator,
889    left: &Distribution,
890    right: &Distribution,
891) -> Result<ScalarValue> {
892    let (left_variance, right_variance) = (left.variance()?, right.variance()?);
893
894    match op {
895        // Note the independence assumption below:
896        Operator::Plus => return left_variance.add_checked(right_variance),
897        // Note the independence assumption below:
898        Operator::Minus => return left_variance.add_checked(right_variance),
899        // Note the independence assumption below:
900        Operator::Multiply => {
901            // For more details, along with an explanation of the formula below, see:
902            //
903            // <https://en.wikipedia.org/wiki/Distribution_of_the_product_of_two_random_variables>
904            let (left_mean, right_mean) = (left.mean()?, right.mean()?);
905            let left_mean_sq = left_mean.mul_checked(&left_mean)?;
906            let right_mean_sq = right_mean.mul_checked(&right_mean)?;
907            let left_sos = left_variance.add_checked(&left_mean_sq)?;
908            let right_sos = right_variance.add_checked(&right_mean_sq)?;
909            let pos = left_mean_sq.mul_checked(right_mean_sq)?;
910            return left_sos.mul_checked(right_sos)?.sub_checked(pos);
911        }
912        // TODO: We can calculate the variance for division when we support reciprocals,
913        // or know the distributions of the operands. For details, see:
914        //
915        // <https://en.wikipedia.org/wiki/Algebra_of_random_variables>
916        // <https://stats.stackexchange.com/questions/185683/distribution-of-ratio-between-two-independent-uniform-random-variables>
917        //
918        // Fall back to an unknown variance value for division:
919        Operator::Divide => {}
920        // Fall back to an unknown variance value for other cases:
921        _ => {}
922    }
923    let target_type = Distribution::target_type(&[&left_variance, &right_variance])?;
924    ScalarValue::try_from(target_type)
925}
926
927#[cfg(test)]
928mod tests {
929    use super::{
930        BernoulliDistribution, Distribution, GaussianDistribution, UniformDistribution,
931        combine_bernoullis, combine_gaussians, compute_mean, compute_median,
932        compute_variance, create_bernoulli_from_comparison, new_generic_from_binary_op,
933    };
934    use crate::interval_arithmetic::{Interval, apply_operator};
935    use crate::operator::Operator;
936
937    use arrow::datatypes::DataType;
938    use datafusion_common::{HashSet, Result, ScalarValue};
939
940    #[test]
941    fn uniform_dist_is_valid_test() -> Result<()> {
942        assert_eq!(
943            Distribution::new_uniform(Interval::make_zero(&DataType::Int8)?)?,
944            Distribution::Uniform(UniformDistribution {
945                interval: Interval::make_zero(&DataType::Int8)?,
946            })
947        );
948
949        assert!(Distribution::new_uniform(Interval::TRUE_OR_FALSE).is_err());
950        Ok(())
951    }
952
953    #[test]
954    fn exponential_dist_is_valid_test() {
955        // This array collects test cases of the form (distribution, validity).
956        let exponentials = vec![
957            (
958                Distribution::new_exponential(ScalarValue::Null, ScalarValue::Null, true),
959                false,
960            ),
961            (
962                Distribution::new_exponential(
963                    ScalarValue::from(0_f32),
964                    ScalarValue::from(1_f32),
965                    true,
966                ),
967                false,
968            ),
969            (
970                Distribution::new_exponential(
971                    ScalarValue::from(100_f32),
972                    ScalarValue::from(1_f32),
973                    true,
974                ),
975                true,
976            ),
977            (
978                Distribution::new_exponential(
979                    ScalarValue::from(-100_f32),
980                    ScalarValue::from(1_f32),
981                    true,
982                ),
983                false,
984            ),
985        ];
986        for case in exponentials {
987            assert_eq!(case.0.is_ok(), case.1);
988        }
989    }
990
991    #[test]
992    fn gaussian_dist_is_valid_test() {
993        // This array collects test cases of the form (distribution, validity).
994        let gaussians = vec![
995            (
996                Distribution::new_gaussian(ScalarValue::Null, ScalarValue::Null),
997                false,
998            ),
999            (
1000                Distribution::new_gaussian(
1001                    ScalarValue::from(0_f32),
1002                    ScalarValue::from(0_f32),
1003                ),
1004                true,
1005            ),
1006            (
1007                Distribution::new_gaussian(
1008                    ScalarValue::from(0_f32),
1009                    ScalarValue::from(0.5_f32),
1010                ),
1011                true,
1012            ),
1013            (
1014                Distribution::new_gaussian(
1015                    ScalarValue::from(0_f32),
1016                    ScalarValue::from(-0.5_f32),
1017                ),
1018                false,
1019            ),
1020        ];
1021        for case in gaussians {
1022            assert_eq!(case.0.is_ok(), case.1);
1023        }
1024    }
1025
1026    #[test]
1027    fn bernoulli_dist_is_valid_test() {
1028        // This array collects test cases of the form (distribution, validity).
1029        let bernoullis = vec![
1030            (Distribution::new_bernoulli(ScalarValue::Null), true),
1031            (Distribution::new_bernoulli(ScalarValue::from(0.)), true),
1032            (Distribution::new_bernoulli(ScalarValue::from(0.25)), true),
1033            (Distribution::new_bernoulli(ScalarValue::from(1.)), true),
1034            (Distribution::new_bernoulli(ScalarValue::from(11.)), false),
1035            (Distribution::new_bernoulli(ScalarValue::from(-11.)), false),
1036            (Distribution::new_bernoulli(ScalarValue::from(0_i64)), true),
1037            (Distribution::new_bernoulli(ScalarValue::from(1_i64)), true),
1038            (
1039                Distribution::new_bernoulli(ScalarValue::from(11_i64)),
1040                false,
1041            ),
1042            (
1043                Distribution::new_bernoulli(ScalarValue::from(-11_i64)),
1044                false,
1045            ),
1046        ];
1047        for case in bernoullis {
1048            assert_eq!(case.0.is_ok(), case.1);
1049        }
1050    }
1051
1052    #[test]
1053    fn generic_dist_is_valid_test() -> Result<()> {
1054        // This array collects test cases of the form (distribution, validity).
1055        let generic_dists = vec![
1056            // Using a boolean range to construct a Generic distribution is prohibited.
1057            (
1058                Distribution::new_generic(
1059                    ScalarValue::Null,
1060                    ScalarValue::Null,
1061                    ScalarValue::Null,
1062                    Interval::TRUE_OR_FALSE,
1063                ),
1064                false,
1065            ),
1066            (
1067                Distribution::new_generic(
1068                    ScalarValue::Null,
1069                    ScalarValue::Null,
1070                    ScalarValue::Null,
1071                    Interval::make_zero(&DataType::Float32)?,
1072                ),
1073                true,
1074            ),
1075            (
1076                Distribution::new_generic(
1077                    ScalarValue::from(0_f32),
1078                    ScalarValue::Float32(None),
1079                    ScalarValue::Float32(None),
1080                    Interval::make_zero(&DataType::Float32)?,
1081                ),
1082                true,
1083            ),
1084            (
1085                Distribution::new_generic(
1086                    ScalarValue::Float64(None),
1087                    ScalarValue::from(0.),
1088                    ScalarValue::Float64(None),
1089                    Interval::make_zero(&DataType::Float32)?,
1090                ),
1091                true,
1092            ),
1093            (
1094                Distribution::new_generic(
1095                    ScalarValue::from(-10_f32),
1096                    ScalarValue::Float32(None),
1097                    ScalarValue::Float32(None),
1098                    Interval::make_zero(&DataType::Float32)?,
1099                ),
1100                false,
1101            ),
1102            (
1103                Distribution::new_generic(
1104                    ScalarValue::Float32(None),
1105                    ScalarValue::from(10_f32),
1106                    ScalarValue::Float32(None),
1107                    Interval::make_zero(&DataType::Float32)?,
1108                ),
1109                false,
1110            ),
1111            (
1112                Distribution::new_generic(
1113                    ScalarValue::Null,
1114                    ScalarValue::Null,
1115                    ScalarValue::Null,
1116                    Interval::make_zero(&DataType::Float32)?,
1117                ),
1118                true,
1119            ),
1120            (
1121                Distribution::new_generic(
1122                    ScalarValue::from(0),
1123                    ScalarValue::from(0),
1124                    ScalarValue::Int32(None),
1125                    Interval::make_zero(&DataType::Int32)?,
1126                ),
1127                true,
1128            ),
1129            (
1130                Distribution::new_generic(
1131                    ScalarValue::from(0_f32),
1132                    ScalarValue::from(0_f32),
1133                    ScalarValue::Float32(None),
1134                    Interval::make_zero(&DataType::Float32)?,
1135                ),
1136                true,
1137            ),
1138            (
1139                Distribution::new_generic(
1140                    ScalarValue::from(50.),
1141                    ScalarValue::from(50.),
1142                    ScalarValue::Float64(None),
1143                    Interval::make(Some(0.), Some(100.))?,
1144                ),
1145                true,
1146            ),
1147            (
1148                Distribution::new_generic(
1149                    ScalarValue::from(50.),
1150                    ScalarValue::from(50.),
1151                    ScalarValue::Float64(None),
1152                    Interval::make(Some(-100.), Some(0.))?,
1153                ),
1154                false,
1155            ),
1156            (
1157                Distribution::new_generic(
1158                    ScalarValue::Float64(None),
1159                    ScalarValue::Float64(None),
1160                    ScalarValue::from(1.),
1161                    Interval::make_zero(&DataType::Float64)?,
1162                ),
1163                true,
1164            ),
1165            (
1166                Distribution::new_generic(
1167                    ScalarValue::Float64(None),
1168                    ScalarValue::Float64(None),
1169                    ScalarValue::from(-1.),
1170                    Interval::make_zero(&DataType::Float64)?,
1171                ),
1172                false,
1173            ),
1174        ];
1175        for case in generic_dists {
1176            assert_eq!(case.0.is_ok(), case.1, "{:?}", case.0);
1177        }
1178
1179        Ok(())
1180    }
1181
1182    #[test]
1183    fn mean_extraction_test() -> Result<()> {
1184        // This array collects test cases of the form (distribution, mean value).
1185        let dists = vec![
1186            (
1187                Distribution::new_uniform(Interval::make_zero(&DataType::Int64)?),
1188                ScalarValue::from(0_i64),
1189            ),
1190            (
1191                Distribution::new_uniform(Interval::make_zero(&DataType::Float64)?),
1192                ScalarValue::from(0.),
1193            ),
1194            (
1195                Distribution::new_uniform(Interval::make(Some(1), Some(100))?),
1196                ScalarValue::from(50),
1197            ),
1198            (
1199                Distribution::new_uniform(Interval::make(Some(-100), Some(-1))?),
1200                ScalarValue::from(-50),
1201            ),
1202            (
1203                Distribution::new_uniform(Interval::make(Some(-100), Some(100))?),
1204                ScalarValue::from(0),
1205            ),
1206            (
1207                Distribution::new_exponential(
1208                    ScalarValue::from(2.),
1209                    ScalarValue::from(0.),
1210                    true,
1211                ),
1212                ScalarValue::from(0.5),
1213            ),
1214            (
1215                Distribution::new_exponential(
1216                    ScalarValue::from(2.),
1217                    ScalarValue::from(1.),
1218                    true,
1219                ),
1220                ScalarValue::from(1.5),
1221            ),
1222            (
1223                Distribution::new_gaussian(ScalarValue::from(0.), ScalarValue::from(1.)),
1224                ScalarValue::from(0.),
1225            ),
1226            (
1227                Distribution::new_gaussian(
1228                    ScalarValue::from(-2.),
1229                    ScalarValue::from(0.5),
1230                ),
1231                ScalarValue::from(-2.),
1232            ),
1233            (
1234                Distribution::new_bernoulli(ScalarValue::from(0.5)),
1235                ScalarValue::from(0.5),
1236            ),
1237            (
1238                Distribution::new_generic(
1239                    ScalarValue::from(42.),
1240                    ScalarValue::from(42.),
1241                    ScalarValue::Float64(None),
1242                    Interval::make(Some(25.), Some(50.))?,
1243                ),
1244                ScalarValue::from(42.),
1245            ),
1246        ];
1247
1248        for case in dists {
1249            assert_eq!(case.0?.mean()?, case.1);
1250        }
1251
1252        Ok(())
1253    }
1254
1255    #[test]
1256    fn median_extraction_test() -> Result<()> {
1257        // This array collects test cases of the form (distribution, median value).
1258        let dists = vec![
1259            (
1260                Distribution::new_uniform(Interval::make_zero(&DataType::Int64)?),
1261                ScalarValue::from(0_i64),
1262            ),
1263            (
1264                Distribution::new_uniform(Interval::make(Some(25.), Some(75.))?),
1265                ScalarValue::from(50.),
1266            ),
1267            (
1268                Distribution::new_exponential(
1269                    ScalarValue::from(2_f64.ln()),
1270                    ScalarValue::from(0.),
1271                    true,
1272                ),
1273                ScalarValue::from(1.),
1274            ),
1275            (
1276                Distribution::new_gaussian(ScalarValue::from(2.), ScalarValue::from(1.)),
1277                ScalarValue::from(2.),
1278            ),
1279            (
1280                Distribution::new_bernoulli(ScalarValue::from(0.25)),
1281                ScalarValue::from(0.),
1282            ),
1283            (
1284                Distribution::new_bernoulli(ScalarValue::from(0.75)),
1285                ScalarValue::from(1.),
1286            ),
1287            (
1288                Distribution::new_gaussian(ScalarValue::from(2.), ScalarValue::from(1.)),
1289                ScalarValue::from(2.),
1290            ),
1291            (
1292                Distribution::new_generic(
1293                    ScalarValue::from(12.),
1294                    ScalarValue::from(12.),
1295                    ScalarValue::Float64(None),
1296                    Interval::make(Some(0.), Some(25.))?,
1297                ),
1298                ScalarValue::from(12.),
1299            ),
1300        ];
1301
1302        for case in dists {
1303            assert_eq!(case.0?.median()?, case.1);
1304        }
1305
1306        Ok(())
1307    }
1308
1309    #[test]
1310    fn variance_extraction_test() -> Result<()> {
1311        // This array collects test cases of the form (distribution, variance value).
1312        let dists = vec![
1313            (
1314                Distribution::new_uniform(Interval::make(Some(0.), Some(12.))?),
1315                ScalarValue::from(12.),
1316            ),
1317            (
1318                Distribution::new_exponential(
1319                    ScalarValue::from(10.),
1320                    ScalarValue::from(0.),
1321                    true,
1322                ),
1323                ScalarValue::from(0.01),
1324            ),
1325            (
1326                Distribution::new_gaussian(ScalarValue::from(0.), ScalarValue::from(1.)),
1327                ScalarValue::from(1.),
1328            ),
1329            (
1330                Distribution::new_bernoulli(ScalarValue::from(0.5)),
1331                ScalarValue::from(0.25),
1332            ),
1333            (
1334                Distribution::new_generic(
1335                    ScalarValue::Float64(None),
1336                    ScalarValue::Float64(None),
1337                    ScalarValue::from(0.02),
1338                    Interval::make_zero(&DataType::Float64)?,
1339                ),
1340                ScalarValue::from(0.02),
1341            ),
1342        ];
1343
1344        for case in dists {
1345            assert_eq!(case.0?.variance()?, case.1);
1346        }
1347
1348        Ok(())
1349    }
1350
1351    #[test]
1352    fn test_calculate_generic_properties_gauss_gauss() -> Result<()> {
1353        let dist_a =
1354            Distribution::new_gaussian(ScalarValue::from(10.), ScalarValue::from(0.0))?;
1355        let dist_b =
1356            Distribution::new_gaussian(ScalarValue::from(20.), ScalarValue::from(0.0))?;
1357
1358        let test_data = vec![
1359            // Mean:
1360            (
1361                compute_mean(&Operator::Plus, &dist_a, &dist_b)?,
1362                ScalarValue::from(30.),
1363            ),
1364            (
1365                compute_mean(&Operator::Minus, &dist_a, &dist_b)?,
1366                ScalarValue::from(-10.),
1367            ),
1368            // Median:
1369            (
1370                compute_median(&Operator::Plus, &dist_a, &dist_b)?,
1371                ScalarValue::from(30.),
1372            ),
1373            (
1374                compute_median(&Operator::Minus, &dist_a, &dist_b)?,
1375                ScalarValue::from(-10.),
1376            ),
1377        ];
1378        for (actual, expected) in test_data {
1379            assert_eq!(actual, expected);
1380        }
1381
1382        Ok(())
1383    }
1384
1385    #[test]
1386    fn test_combine_bernoullis_and_op() -> Result<()> {
1387        let op = Operator::And;
1388        let left = BernoulliDistribution::try_new(ScalarValue::from(0.5))?;
1389        let right = BernoulliDistribution::try_new(ScalarValue::from(0.4))?;
1390        let left_null = BernoulliDistribution::try_new(ScalarValue::Null)?;
1391        let right_null = BernoulliDistribution::try_new(ScalarValue::Null)?;
1392
1393        assert_eq!(
1394            combine_bernoullis(&op, &left, &right)?.p_value(),
1395            &ScalarValue::from(0.5 * 0.4)
1396        );
1397        assert_eq!(
1398            combine_bernoullis(&op, &left_null, &right)?.p_value(),
1399            &ScalarValue::Float64(None)
1400        );
1401        assert_eq!(
1402            combine_bernoullis(&op, &left, &right_null)?.p_value(),
1403            &ScalarValue::Float64(None)
1404        );
1405        assert_eq!(
1406            combine_bernoullis(&op, &left_null, &left_null)?.p_value(),
1407            &ScalarValue::Null
1408        );
1409
1410        Ok(())
1411    }
1412
1413    #[test]
1414    fn test_combine_bernoullis_or_op() -> Result<()> {
1415        let op = Operator::Or;
1416        let left = BernoulliDistribution::try_new(ScalarValue::from(0.6))?;
1417        let right = BernoulliDistribution::try_new(ScalarValue::from(0.4))?;
1418        let left_null = BernoulliDistribution::try_new(ScalarValue::Null)?;
1419        let right_null = BernoulliDistribution::try_new(ScalarValue::Null)?;
1420
1421        assert_eq!(
1422            combine_bernoullis(&op, &left, &right)?.p_value(),
1423            &ScalarValue::from(0.6 + 0.4 - (0.6 * 0.4))
1424        );
1425        assert_eq!(
1426            combine_bernoullis(&op, &left_null, &right)?.p_value(),
1427            &ScalarValue::Float64(None)
1428        );
1429        assert_eq!(
1430            combine_bernoullis(&op, &left, &right_null)?.p_value(),
1431            &ScalarValue::Float64(None)
1432        );
1433        assert_eq!(
1434            combine_bernoullis(&op, &left_null, &left_null)?.p_value(),
1435            &ScalarValue::Null
1436        );
1437
1438        Ok(())
1439    }
1440
1441    #[test]
1442    fn test_combine_bernoullis_unsupported_ops() -> Result<()> {
1443        let mut operator_set = operator_set();
1444        operator_set.remove(&Operator::And);
1445        operator_set.remove(&Operator::Or);
1446
1447        let left = BernoulliDistribution::try_new(ScalarValue::from(0.6))?;
1448        let right = BernoulliDistribution::try_new(ScalarValue::from(0.4))?;
1449        for op in operator_set {
1450            assert!(
1451                combine_bernoullis(&op, &left, &right).is_err(),
1452                "Operator {op} should not be supported for Bernoulli distributions"
1453            );
1454        }
1455
1456        Ok(())
1457    }
1458
1459    #[test]
1460    fn test_combine_gaussians_addition() -> Result<()> {
1461        let op = Operator::Plus;
1462        let left = GaussianDistribution::try_new(
1463            ScalarValue::from(3.0),
1464            ScalarValue::from(2.0),
1465        )?;
1466        let right = GaussianDistribution::try_new(
1467            ScalarValue::from(4.0),
1468            ScalarValue::from(1.0),
1469        )?;
1470
1471        let result = combine_gaussians(&op, &left, &right)?.unwrap();
1472
1473        assert_eq!(result.mean(), &ScalarValue::from(7.0)); // 3.0 + 4.0
1474        assert_eq!(result.variance(), &ScalarValue::from(3.0)); // 2.0 + 1.0
1475        Ok(())
1476    }
1477
1478    #[test]
1479    fn test_combine_gaussians_subtraction() -> Result<()> {
1480        let op = Operator::Minus;
1481        let left = GaussianDistribution::try_new(
1482            ScalarValue::from(7.0),
1483            ScalarValue::from(2.0),
1484        )?;
1485        let right = GaussianDistribution::try_new(
1486            ScalarValue::from(4.0),
1487            ScalarValue::from(1.0),
1488        )?;
1489
1490        let result = combine_gaussians(&op, &left, &right)?.unwrap();
1491
1492        assert_eq!(result.mean(), &ScalarValue::from(3.0)); // 7.0 - 4.0
1493        assert_eq!(result.variance(), &ScalarValue::from(3.0)); // 2.0 + 1.0
1494
1495        Ok(())
1496    }
1497
1498    #[test]
1499    fn test_combine_gaussians_unsupported_ops() -> Result<()> {
1500        let mut operator_set = operator_set();
1501        operator_set.remove(&Operator::Plus);
1502        operator_set.remove(&Operator::Minus);
1503
1504        let left = GaussianDistribution::try_new(
1505            ScalarValue::from(7.0),
1506            ScalarValue::from(2.0),
1507        )?;
1508        let right = GaussianDistribution::try_new(
1509            ScalarValue::from(4.0),
1510            ScalarValue::from(1.0),
1511        )?;
1512        for op in operator_set {
1513            assert!(
1514                combine_gaussians(&op, &left, &right)?.is_none(),
1515                "Operator {op} should not be supported for Gaussian distributions"
1516            );
1517        }
1518
1519        Ok(())
1520    }
1521
1522    // Expected test results were calculated in Wolfram Mathematica, by using:
1523    //
1524    // *METHOD_NAME*[TransformedDistribution[
1525    //  x *op* y,
1526    //  {x ~ *DISTRIBUTION_X*[..], y ~ *DISTRIBUTION_Y*[..]}
1527    // ]]
1528    #[test]
1529    fn test_calculate_generic_properties_uniform_uniform() -> Result<()> {
1530        let dist_a = Distribution::new_uniform(Interval::make(Some(0.), Some(12.))?)?;
1531        let dist_b = Distribution::new_uniform(Interval::make(Some(12.), Some(36.))?)?;
1532
1533        let test_data = vec![
1534            // Mean:
1535            (
1536                compute_mean(&Operator::Plus, &dist_a, &dist_b)?,
1537                ScalarValue::from(30.),
1538            ),
1539            (
1540                compute_mean(&Operator::Minus, &dist_a, &dist_b)?,
1541                ScalarValue::from(-18.),
1542            ),
1543            (
1544                compute_mean(&Operator::Multiply, &dist_a, &dist_b)?,
1545                ScalarValue::from(144.),
1546            ),
1547            // Median:
1548            (
1549                compute_median(&Operator::Plus, &dist_a, &dist_b)?,
1550                ScalarValue::from(30.),
1551            ),
1552            (
1553                compute_median(&Operator::Minus, &dist_a, &dist_b)?,
1554                ScalarValue::from(-18.),
1555            ),
1556            // Variance:
1557            (
1558                compute_variance(&Operator::Plus, &dist_a, &dist_b)?,
1559                ScalarValue::from(60.),
1560            ),
1561            (
1562                compute_variance(&Operator::Minus, &dist_a, &dist_b)?,
1563                ScalarValue::from(60.),
1564            ),
1565            (
1566                compute_variance(&Operator::Multiply, &dist_a, &dist_b)?,
1567                ScalarValue::from(9216.),
1568            ),
1569        ];
1570        for (actual, expected) in test_data {
1571            assert_eq!(actual, expected);
1572        }
1573
1574        Ok(())
1575    }
1576
1577    /// Test for `Uniform`-`Uniform`, `Uniform`-`Generic`, `Generic`-`Uniform`,
1578    /// `Generic`-`Generic` pairs, where range is always present.
1579    #[test]
1580    fn test_compute_range_where_present() -> Result<()> {
1581        let a = &Interval::make(Some(0.), Some(12.0))?;
1582        let b = &Interval::make(Some(0.), Some(12.0))?;
1583        let mean = ScalarValue::from(6.0);
1584        for (dist_a, dist_b) in [
1585            (
1586                Distribution::new_uniform(a.clone())?,
1587                Distribution::new_uniform(b.clone())?,
1588            ),
1589            (
1590                Distribution::new_generic(
1591                    mean.clone(),
1592                    mean.clone(),
1593                    ScalarValue::Float64(None),
1594                    a.clone(),
1595                )?,
1596                Distribution::new_uniform(b.clone())?,
1597            ),
1598            (
1599                Distribution::new_uniform(a.clone())?,
1600                Distribution::new_generic(
1601                    mean.clone(),
1602                    mean.clone(),
1603                    ScalarValue::Float64(None),
1604                    b.clone(),
1605                )?,
1606            ),
1607            (
1608                Distribution::new_generic(
1609                    mean.clone(),
1610                    mean.clone(),
1611                    ScalarValue::Float64(None),
1612                    a.clone(),
1613                )?,
1614                Distribution::new_generic(
1615                    mean.clone(),
1616                    mean.clone(),
1617                    ScalarValue::Float64(None),
1618                    b.clone(),
1619                )?,
1620            ),
1621        ] {
1622            use super::Operator::{
1623                Divide, Eq, Gt, GtEq, Lt, LtEq, Minus, Multiply, NotEq, Plus,
1624            };
1625            for op in [Plus, Minus, Multiply, Divide] {
1626                assert_eq!(
1627                    new_generic_from_binary_op(&op, &dist_a, &dist_b)?.range()?,
1628                    apply_operator(&op, a, b)?,
1629                    "Failed for {dist_a:?} {op} {dist_b:?}"
1630                );
1631            }
1632            for op in [Gt, GtEq, Lt, LtEq, Eq, NotEq] {
1633                assert_eq!(
1634                    create_bernoulli_from_comparison(&op, &dist_a, &dist_b)?.range()?,
1635                    apply_operator(&op, a, b)?,
1636                    "Failed for {dist_a:?} {op} {dist_b:?}"
1637                );
1638            }
1639        }
1640
1641        Ok(())
1642    }
1643
1644    fn operator_set() -> HashSet<Operator> {
1645        use super::Operator::*;
1646
1647        let all_ops = vec![
1648            And,
1649            Or,
1650            Eq,
1651            NotEq,
1652            Gt,
1653            GtEq,
1654            Lt,
1655            LtEq,
1656            Plus,
1657            Minus,
1658            Multiply,
1659            Divide,
1660            Modulo,
1661            IsDistinctFrom,
1662            IsNotDistinctFrom,
1663            RegexMatch,
1664            RegexIMatch,
1665            RegexNotMatch,
1666            RegexNotIMatch,
1667            LikeMatch,
1668            ILikeMatch,
1669            NotLikeMatch,
1670            NotILikeMatch,
1671            BitwiseAnd,
1672            BitwiseOr,
1673            BitwiseXor,
1674            BitwiseShiftRight,
1675            BitwiseShiftLeft,
1676            StringConcat,
1677            AtArrow,
1678            ArrowAt,
1679        ];
1680
1681        all_ops.into_iter().collect()
1682    }
1683}
1684
1685use std::sync::Arc;
1686
1687use datafusion_common::Column;
1688
1689/// A statistic a caller would like a provider to supply, if it can do so
1690/// cheaply.
1691///
1692/// A small, query-aware extension to the existing `Statistics` model: instead
1693/// of "give me everything you have for every column", a caller can ask for a
1694/// specific list of stats by name. `StatisticsRequest` is just that vocabulary
1695/// — DataFusion itself does not populate or consume it. It exists so a request
1696/// can be threaded from a `TableScan` (see `TableScan::statistics_requests`)
1697/// through `ScanArgs::statistics_requests` to a `TableProvider`, which is enough
1698/// for a query-aware statistics feature to be implemented outside of DataFusion.
1699///
1700/// Each variant maps onto a field of [`datafusion_common::Statistics`] /
1701/// [`datafusion_common::ColumnStatistics`], so a provider that already
1702/// populates one can answer the request trivially.
1703///
1704/// The per-column variants hold an `Arc<Column>` rather than an owned
1705/// [`Column`] (which carries owned strings) so cloning a request — and the
1706/// `BTreeSet<StatisticsRequest>` stored on `TableScan`, which is cloned with
1707/// the plan during optimization — stays cheap.
1708#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
1709pub enum StatisticsRequest {
1710    /// Smallest non-null value of `column`.
1711    Min(Arc<Column>),
1712    /// Largest non-null value of `column`.
1713    Max(Arc<Column>),
1714    /// Number of NULLs in `column`.
1715    NullCount(Arc<Column>),
1716    /// Number of distinct values in `column` (exact or estimated).
1717    DistinctCount(Arc<Column>),
1718    /// Sum of values in `column` (numerics, widened per
1719    /// `ColumnStatistics::sum_value`).
1720    Sum(Arc<Column>),
1721    /// Encoded/output byte size of `column`.
1722    ByteSize(Arc<Column>),
1723    /// Number of rows in the container (table / file).
1724    RowCount,
1725    /// Total byte size of the container's output.
1726    TotalByteSize,
1727}