1#![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#[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 pub fn new_uniform(interval: Interval) -> Result<Self> {
55 UniformDistribution::try_new(interval).map(Uniform)
56 }
57
58 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 pub fn new_gaussian(mean: ScalarValue, variance: ScalarValue) -> Result<Self> {
71 GaussianDistribution::try_new(mean, variance).map(Gaussian)
72 }
73
74 pub fn new_bernoulli(p: ScalarValue) -> Result<Self> {
77 BernoulliDistribution::try_new(p).map(Bernoulli)
78 }
79
80 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 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 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 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 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 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 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#[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#[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 positive_tail: bool,
255}
256
257#[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#[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#[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 pub fn mean(&self) -> Result<ScalarValue> {
319 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 pub fn variance(&self) -> Result<ScalarValue> {
341 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 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 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 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 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 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 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 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#[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#[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#[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 let (Some(lc), Some(rc), Some(ic)) = (
723 li.cardinality(),
724 ri.cardinality(),
725 intersection.cardinality(),
726 ) {
727 let pairs = ((lc as u128) * (rc as u128)) as f64;
729 let p = (ic as f64).div_checked(pairs)?;
730 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 return Distribution::new_bernoulli(ScalarValue::from(0.0));
749 } else {
750 return Distribution::new_bernoulli(ScalarValue::from(1.0));
752 }
753 }
754 Operator::Lt | Operator::LtEq | Operator::Gt | Operator::GtEq => {
755 }
761 _ => {}
762 }
763 }
764 (Gaussian(_), Gaussian(_)) => {
765 }
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#[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#[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 Operator::Multiply => return left_mean.mul_checked(right_mean),
822 Operator::Divide => {}
830 _ => {}
832 }
833 let target_type = Distribution::target_type(&[&left_mean, &right_mean])?;
834 ScalarValue::try_from(target_type)
835}
836
837#[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 match op {
858 Operator::Plus => return left_median.add_checked(right_median),
859 Operator::Minus => return left_median.sub_checked(right_median),
860 _ => {}
862 }
863 }
864 (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 _ => {}
871 },
872 _ => {}
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#[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 Operator::Plus => return left_variance.add_checked(right_variance),
897 Operator::Minus => return left_variance.add_checked(right_variance),
899 Operator::Multiply => {
901 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 Operator::Divide => {}
920 _ => {}
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 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 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 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 let generic_dists = vec![
1056 (
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 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 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 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 (
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 (
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)); assert_eq!(result.variance(), &ScalarValue::from(3.0)); 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)); assert_eq!(result.variance(), &ScalarValue::from(3.0)); 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 #[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 (
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 (
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 (
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]
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#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
1709pub enum StatisticsRequest {
1710 Min(Arc<Column>),
1712 Max(Arc<Column>),
1714 NullCount(Arc<Column>),
1716 DistinctCount(Arc<Column>),
1718 Sum(Arc<Column>),
1721 ByteSize(Arc<Column>),
1723 RowCount,
1725 TotalByteSize,
1727}