-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
interval_aritmetic.rs
1942 lines (1811 loc) · 69.3 KB
/
interval_aritmetic.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//! Interval arithmetic library
use std::borrow::Borrow;
use std::fmt::{self, Display, Formatter};
use std::ops::{AddAssign, SubAssign};
use crate::aggregate::min_max::{max, min};
use crate::intervals::rounding::{alter_fp_rounding_mode, next_down, next_up};
use arrow::compute::{cast_with_options, CastOptions};
use arrow::datatypes::DataType;
use arrow_array::ArrowNativeTypeOp;
use datafusion_common::{internal_err, DataFusionError, Result, ScalarValue};
use datafusion_expr::type_coercion::binary::get_result_type;
use datafusion_expr::Operator;
/// This type represents a single endpoint of an [`Interval`]. An
/// endpoint can be open (does not include the endpoint) or closed
/// (includes the endpoint).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IntervalBound {
pub value: ScalarValue,
/// If true, interval does not include `value`
pub open: bool,
}
impl IntervalBound {
/// Creates a new `IntervalBound` object using the given value.
pub const fn new(value: ScalarValue, open: bool) -> IntervalBound {
IntervalBound { value, open }
}
/// Creates a new "open" interval (does not include the `value`
/// bound)
pub const fn new_open(value: ScalarValue) -> IntervalBound {
IntervalBound::new(value, true)
}
/// Creates a new "closed" interval (includes the `value`
/// bound)
pub const fn new_closed(value: ScalarValue) -> IntervalBound {
IntervalBound::new(value, false)
}
/// This convenience function creates an unbounded interval endpoint.
pub fn make_unbounded<T: Borrow<DataType>>(data_type: T) -> Result<Self> {
ScalarValue::try_from(data_type.borrow()).map(|v| IntervalBound::new(v, true))
}
/// This convenience function returns the data type associated with this
/// `IntervalBound`.
pub fn get_datatype(&self) -> DataType {
self.value.data_type()
}
/// This convenience function checks whether the `IntervalBound` represents
/// an unbounded interval endpoint.
pub fn is_unbounded(&self) -> bool {
self.value.is_null()
}
/// This function casts the `IntervalBound` to the given data type.
pub(crate) fn cast_to(
&self,
data_type: &DataType,
cast_options: &CastOptions,
) -> Result<IntervalBound> {
cast_scalar_value(&self.value, data_type, cast_options)
.map(|value| IntervalBound::new(value, self.open))
}
/// Returns a new bound with a negated value, if any, and the same open/closed.
/// For example negating `[5` would return `[-5`, or `-1)` would return `1)`.
pub fn negate(&self) -> Result<IntervalBound> {
self.value.arithmetic_negate().map(|value| IntervalBound {
value,
open: self.open,
})
}
/// This function adds the given `IntervalBound` to this `IntervalBound`.
/// The result is unbounded if either is; otherwise, their values are
/// added. The result is closed if both original bounds are closed, or open
/// otherwise.
pub fn add<const UPPER: bool, T: Borrow<IntervalBound>>(
&self,
other: T,
) -> Result<IntervalBound> {
let rhs = other.borrow();
if self.is_unbounded() || rhs.is_unbounded() {
return IntervalBound::make_unbounded(get_result_type(
&self.get_datatype(),
&Operator::Plus,
&rhs.get_datatype(),
)?);
}
match self.get_datatype() {
DataType::Float64 | DataType::Float32 => {
alter_fp_rounding_mode::<UPPER, _>(&self.value, &rhs.value, |lhs, rhs| {
lhs.add(rhs)
})
}
_ => self.value.add(&rhs.value),
}
.map(|v| IntervalBound::new(v, self.open || rhs.open))
}
/// This function subtracts the given `IntervalBound` from `self`.
/// The result is unbounded if either is; otherwise, their values are
/// subtracted. The result is closed if both original bounds are closed,
/// or open otherwise.
pub fn sub<const UPPER: bool, T: Borrow<IntervalBound>>(
&self,
other: T,
) -> Result<IntervalBound> {
let rhs = other.borrow();
if self.is_unbounded() || rhs.is_unbounded() {
return IntervalBound::make_unbounded(get_result_type(
&self.get_datatype(),
&Operator::Minus,
&rhs.get_datatype(),
)?);
}
match self.get_datatype() {
DataType::Float64 | DataType::Float32 => {
alter_fp_rounding_mode::<UPPER, _>(&self.value, &rhs.value, |lhs, rhs| {
lhs.sub(rhs)
})
}
_ => self.value.sub(&rhs.value),
}
.map(|v| IntervalBound::new(v, self.open || rhs.open))
}
/// This function chooses one of the given `IntervalBound`s according to
/// the given function `decide`. The result is unbounded if both are. If
/// only one of the arguments is unbounded, the other one is chosen by
/// default. If neither is unbounded, the function `decide` is used.
pub fn choose(
first: &IntervalBound,
second: &IntervalBound,
decide: fn(&ScalarValue, &ScalarValue) -> Result<ScalarValue>,
) -> Result<IntervalBound> {
Ok(if first.is_unbounded() {
second.clone()
} else if second.is_unbounded() {
first.clone()
} else if first.value != second.value {
let chosen = decide(&first.value, &second.value)?;
if chosen.eq(&first.value) {
first.clone()
} else {
second.clone()
}
} else {
IntervalBound::new(second.value.clone(), first.open || second.open)
})
}
}
impl Display for IntervalBound {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "IntervalBound [{}]", self.value)
}
}
/// This type represents an interval, which is used to calculate reliable
/// bounds for expressions:
///
/// * An *open* interval does not include the endpoint and is written using a
/// `(` or `)`.
///
/// * A *closed* interval does include the endpoint and is written using `[` or
/// `]`.
///
/// * If the interval's `lower` and/or `upper` bounds are not known, they are
/// called *unbounded* endpoint and represented using a `NULL` and written using
/// `∞`.
///
/// # Examples
///
/// A `Int64` `Interval` of `[10, 20)` represents the values `10, 11, ... 18,
/// 19` (includes 10, but does not include 20).
///
/// A `Int64` `Interval` of `[10, ∞)` represents a value known to be either
/// `10` or higher.
///
/// An `Interval` of `(-∞, ∞)` represents that the range is entirely unknown.
///
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Interval {
pub lower: IntervalBound,
pub upper: IntervalBound,
}
impl Default for Interval {
fn default() -> Self {
Interval::new(
IntervalBound::new(ScalarValue::Null, true),
IntervalBound::new(ScalarValue::Null, true),
)
}
}
impl Display for Interval {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(
f,
"{}{}, {}{}",
if self.lower.open { "(" } else { "[" },
self.lower.value,
self.upper.value,
if self.upper.open { ")" } else { "]" }
)
}
}
impl Interval {
/// Creates a new interval object using the given bounds.
///
/// # Boolean intervals need special handling
///
/// For boolean intervals, having an open false lower bound is equivalent to
/// having a true closed lower bound. Similarly, open true upper bound is
/// equivalent to having a false closed upper bound. Also for boolean
/// intervals, having an unbounded left endpoint is equivalent to having a
/// false closed lower bound, while having an unbounded right endpoint is
/// equivalent to having a true closed upper bound. Therefore; input
/// parameters to construct an Interval can have different types, but they
/// all result in `[false, false]`, `[false, true]` or `[true, true]`.
pub fn new(lower: IntervalBound, upper: IntervalBound) -> Interval {
// Boolean intervals need a special handling.
if let ScalarValue::Boolean(_) = lower.value {
let standardized_lower = match lower.value {
ScalarValue::Boolean(None) if lower.open => {
ScalarValue::Boolean(Some(false))
}
ScalarValue::Boolean(Some(false)) if lower.open => {
ScalarValue::Boolean(Some(true))
}
// The rest may include some invalid interval cases. The validation of
// interval construction parameters will be implemented later.
// For now, let's return them unchanged.
_ => lower.value,
};
let standardized_upper = match upper.value {
ScalarValue::Boolean(None) if upper.open => {
ScalarValue::Boolean(Some(true))
}
ScalarValue::Boolean(Some(true)) if upper.open => {
ScalarValue::Boolean(Some(false))
}
_ => upper.value,
};
Interval {
lower: IntervalBound::new(standardized_lower, false),
upper: IntervalBound::new(standardized_upper, false),
}
} else {
Interval { lower, upper }
}
}
pub fn make<T>(lower: Option<T>, upper: Option<T>, open: (bool, bool)) -> Interval
where
ScalarValue: From<Option<T>>,
{
Interval::new(
IntervalBound::new(ScalarValue::from(lower), open.0),
IntervalBound::new(ScalarValue::from(upper), open.1),
)
}
/// Casts this interval to `data_type` using `cast_options`.
pub(crate) fn cast_to(
&self,
data_type: &DataType,
cast_options: &CastOptions,
) -> Result<Interval> {
let lower = self.lower.cast_to(data_type, cast_options)?;
let upper = self.upper.cast_to(data_type, cast_options)?;
Ok(Interval::new(lower, upper))
}
/// This function returns the data type of this interval. If both endpoints
/// do not have the same data type, returns an error.
pub fn get_datatype(&self) -> Result<DataType> {
let lower_type = self.lower.get_datatype();
let upper_type = self.upper.get_datatype();
if lower_type == upper_type {
Ok(lower_type)
} else {
internal_err!(
"Interval bounds have different types: {lower_type} != {upper_type}"
)
}
}
/// Decide if this interval is certainly greater than, possibly greater than,
/// or can't be greater than `other` by returning [true, true],
/// [false, true] or [false, false] respectively.
pub(crate) fn gt<T: Borrow<Interval>>(&self, other: T) -> Interval {
let rhs = other.borrow();
let flags = if !self.upper.is_unbounded()
&& !rhs.lower.is_unbounded()
&& self.upper.value <= rhs.lower.value
{
// Values in this interval are certainly less than or equal to those
// in the given interval.
(false, false)
} else if !self.lower.is_unbounded()
&& !rhs.upper.is_unbounded()
&& self.lower.value >= rhs.upper.value
&& (self.lower.value > rhs.upper.value || self.lower.open || rhs.upper.open)
{
// Values in this interval are certainly greater than those in the
// given interval.
(true, true)
} else {
// All outcomes are possible.
(false, true)
};
Interval::make(Some(flags.0), Some(flags.1), (false, false))
}
/// Decide if this interval is certainly greater than or equal to, possibly greater than
/// or equal to, or can't be greater than or equal to `other` by returning [true, true],
/// [false, true] or [false, false] respectively.
pub(crate) fn gt_eq<T: Borrow<Interval>>(&self, other: T) -> Interval {
let rhs = other.borrow();
let flags = if !self.lower.is_unbounded()
&& !rhs.upper.is_unbounded()
&& self.lower.value >= rhs.upper.value
{
// Values in this interval are certainly greater than or equal to those
// in the given interval.
(true, true)
} else if !self.upper.is_unbounded()
&& !rhs.lower.is_unbounded()
&& self.upper.value <= rhs.lower.value
&& (self.upper.value < rhs.lower.value || self.upper.open || rhs.lower.open)
{
// Values in this interval are certainly less than those in the
// given interval.
(false, false)
} else {
// All outcomes are possible.
(false, true)
};
Interval::make(Some(flags.0), Some(flags.1), (false, false))
}
/// Decide if this interval is certainly less than, possibly less than,
/// or can't be less than `other` by returning [true, true],
/// [false, true] or [false, false] respectively.
pub(crate) fn lt<T: Borrow<Interval>>(&self, other: T) -> Interval {
other.borrow().gt(self)
}
/// Decide if this interval is certainly less than or equal to, possibly
/// less than or equal to, or can't be less than or equal to `other` by returning
/// [true, true], [false, true] or [false, false] respectively.
pub(crate) fn lt_eq<T: Borrow<Interval>>(&self, other: T) -> Interval {
other.borrow().gt_eq(self)
}
/// Decide if this interval is certainly equal to, possibly equal to,
/// or can't be equal to `other` by returning [true, true],
/// [false, true] or [false, false] respectively.
pub(crate) fn equal<T: Borrow<Interval>>(&self, other: T) -> Interval {
let rhs = other.borrow();
let flags = if !self.lower.is_unbounded()
&& (self.lower.value == self.upper.value)
&& (rhs.lower.value == rhs.upper.value)
&& (self.lower.value == rhs.lower.value)
{
(true, true)
} else if self.gt(rhs) == Interval::CERTAINLY_TRUE
|| self.lt(rhs) == Interval::CERTAINLY_TRUE
{
(false, false)
} else {
(false, true)
};
Interval::make(Some(flags.0), Some(flags.1), (false, false))
}
/// Compute the logical conjunction of this (boolean) interval with the given boolean interval.
pub(crate) fn and<T: Borrow<Interval>>(&self, other: T) -> Result<Interval> {
let rhs = other.borrow();
match (
&self.lower.value,
&self.upper.value,
&rhs.lower.value,
&rhs.upper.value,
) {
(
ScalarValue::Boolean(Some(self_lower)),
ScalarValue::Boolean(Some(self_upper)),
ScalarValue::Boolean(Some(other_lower)),
ScalarValue::Boolean(Some(other_upper)),
) => {
let lower = *self_lower && *other_lower;
let upper = *self_upper && *other_upper;
Ok(Interval {
lower: IntervalBound::new(ScalarValue::Boolean(Some(lower)), false),
upper: IntervalBound::new(ScalarValue::Boolean(Some(upper)), false),
})
}
_ => internal_err!("Incompatible types for logical conjunction"),
}
}
/// Compute the logical disjunction of this (boolean) interval with the given boolean interval.
pub(crate) fn or<T: Borrow<Interval>>(&self, other: T) -> Result<Interval> {
let rhs = other.borrow();
match (
&self.lower.value,
&self.upper.value,
&rhs.lower.value,
&rhs.upper.value,
) {
(
ScalarValue::Boolean(Some(self_lower)),
ScalarValue::Boolean(Some(self_upper)),
ScalarValue::Boolean(Some(other_lower)),
ScalarValue::Boolean(Some(other_upper)),
) => {
let lower = *self_lower || *other_lower;
let upper = *self_upper || *other_upper;
Ok(Interval {
lower: IntervalBound::new(ScalarValue::Boolean(Some(lower)), false),
upper: IntervalBound::new(ScalarValue::Boolean(Some(upper)), false),
})
}
_ => internal_err!("Incompatible types for logical disjunction"),
}
}
/// Compute the logical negation of this (boolean) interval.
pub(crate) fn not(&self) -> Result<Self> {
if !matches!(self.get_datatype()?, DataType::Boolean) {
return internal_err!(
"Cannot apply logical negation to non-boolean interval"
);
}
if self == &Interval::CERTAINLY_TRUE {
Ok(Interval::CERTAINLY_FALSE)
} else if self == &Interval::CERTAINLY_FALSE {
Ok(Interval::CERTAINLY_TRUE)
} else {
Ok(Interval::UNCERTAIN)
}
}
/// Compute the intersection of the interval with the given interval.
/// If the intersection is empty, return None.
pub(crate) fn intersect<T: Borrow<Interval>>(
&self,
other: T,
) -> Result<Option<Interval>> {
let rhs = other.borrow();
// If it is evident that the result is an empty interval,
// do not make any calculation and directly return None.
if (!self.lower.is_unbounded()
&& !rhs.upper.is_unbounded()
&& self.lower.value > rhs.upper.value)
|| (!self.upper.is_unbounded()
&& !rhs.lower.is_unbounded()
&& self.upper.value < rhs.lower.value)
{
// This None value signals an empty interval.
return Ok(None);
}
let lower = IntervalBound::choose(&self.lower, &rhs.lower, max)?;
let upper = IntervalBound::choose(&self.upper, &rhs.upper, min)?;
let non_empty = lower.is_unbounded()
|| upper.is_unbounded()
|| lower.value != upper.value
|| (!lower.open && !upper.open);
Ok(non_empty.then_some(Interval::new(lower, upper)))
}
/// Decide if this interval is certainly contains, possibly contains,
/// or can't can't `other` by returning [true, true],
/// [false, true] or [false, false] respectively.
pub fn contains<T: Borrow<Self>>(&self, other: T) -> Result<Self> {
match self.intersect(other.borrow())? {
Some(intersection) => {
// Need to compare with same bounds close-ness.
if intersection.close_bounds() == other.borrow().clone().close_bounds() {
Ok(Interval::CERTAINLY_TRUE)
} else {
Ok(Interval::UNCERTAIN)
}
}
None => Ok(Interval::CERTAINLY_FALSE),
}
}
/// Add the given interval (`other`) to this interval. Say we have
/// intervals [a1, b1] and [a2, b2], then their sum is [a1 + a2, b1 + b2].
/// Note that this represents all possible values the sum can take if
/// one can choose single values arbitrarily from each of the operands.
pub fn add<T: Borrow<Interval>>(&self, other: T) -> Result<Interval> {
let rhs = other.borrow();
Ok(Interval::new(
self.lower.add::<false, _>(&rhs.lower)?,
self.upper.add::<true, _>(&rhs.upper)?,
))
}
/// Subtract the given interval (`other`) from this interval. Say we have
/// intervals [a1, b1] and [a2, b2], then their sum is [a1 - b2, b1 - a2].
/// Note that this represents all possible values the difference can take
/// if one can choose single values arbitrarily from each of the operands.
pub fn sub<T: Borrow<Interval>>(&self, other: T) -> Result<Interval> {
let rhs = other.borrow();
Ok(Interval::new(
self.lower.sub::<false, _>(&rhs.upper)?,
self.upper.sub::<true, _>(&rhs.lower)?,
))
}
pub const CERTAINLY_FALSE: Interval = Interval {
lower: IntervalBound::new_closed(ScalarValue::Boolean(Some(false))),
upper: IntervalBound::new_closed(ScalarValue::Boolean(Some(false))),
};
pub const UNCERTAIN: Interval = Interval {
lower: IntervalBound::new_closed(ScalarValue::Boolean(Some(false))),
upper: IntervalBound::new_closed(ScalarValue::Boolean(Some(true))),
};
pub const CERTAINLY_TRUE: Interval = Interval {
lower: IntervalBound::new_closed(ScalarValue::Boolean(Some(true))),
upper: IntervalBound::new_closed(ScalarValue::Boolean(Some(true))),
};
/// Returns the cardinality of this interval, which is the number of all
/// distinct points inside it. This function returns `None` if:
/// - The interval is unbounded from either side, or
/// - Cardinality calculations for the datatype in question is not
/// implemented yet, or
/// - An overflow occurs during the calculation.
///
/// This function returns an error if the given interval is malformed.
pub fn cardinality(&self) -> Result<Option<u64>> {
let data_type = self.get_datatype()?;
if data_type.is_integer() {
Ok(self.upper.value.distance(&self.lower.value).map(|diff| {
calculate_cardinality_based_on_bounds(
self.lower.open,
self.upper.open,
diff as u64,
)
}))
}
// Ordering floating-point numbers according to their binary representations
// coincide with their natural ordering. Therefore, we can consider their
// binary representations as "indices" and subtract them. For details, see:
// https://stackoverflow.com/questions/8875064/how-many-distinct-floating-point-numbers-in-a-specific-range
else if data_type.is_floating() {
match (&self.lower.value, &self.upper.value) {
(
ScalarValue::Float32(Some(lower)),
ScalarValue::Float32(Some(upper)),
) => {
// Negative numbers are sorted in the reverse order. To always have a positive difference after the subtraction,
// we perform following transformation:
let lower_bits = lower.to_bits() as i32;
let upper_bits = upper.to_bits() as i32;
let transformed_lower =
lower_bits ^ ((lower_bits >> 31) & 0x7fffffff);
let transformed_upper =
upper_bits ^ ((upper_bits >> 31) & 0x7fffffff);
let Ok(count) = transformed_upper.sub_checked(transformed_lower)
else {
return Ok(None);
};
Ok(Some(calculate_cardinality_based_on_bounds(
self.lower.open,
self.upper.open,
count as u64,
)))
}
(
ScalarValue::Float64(Some(lower)),
ScalarValue::Float64(Some(upper)),
) => {
let lower_bits = lower.to_bits() as i64;
let upper_bits = upper.to_bits() as i64;
let transformed_lower =
lower_bits ^ ((lower_bits >> 63) & 0x7fffffffffffffff);
let transformed_upper =
upper_bits ^ ((upper_bits >> 63) & 0x7fffffffffffffff);
let Ok(count) = transformed_upper.sub_checked(transformed_lower)
else {
return Ok(None);
};
Ok(Some(calculate_cardinality_based_on_bounds(
self.lower.open,
self.upper.open,
count as u64,
)))
}
_ => Ok(None),
}
} else {
// Cardinality calculations are not implemented for this data type yet:
Ok(None)
}
}
/// This function "closes" this interval; i.e. it modifies the endpoints so
/// that we end up with the narrowest possible closed interval containing
/// the original interval.
pub fn close_bounds(mut self) -> Interval {
if self.lower.open {
// Get next value
self.lower.value = next_value::<true>(self.lower.value);
self.lower.open = false;
}
if self.upper.open {
// Get previous value
self.upper.value = next_value::<false>(self.upper.value);
self.upper.open = false;
}
self
}
}
trait OneTrait: Sized + std::ops::Add + std::ops::Sub {
fn one() -> Self;
}
macro_rules! impl_OneTrait{
($($m:ty),*) => {$( impl OneTrait for $m { fn one() -> Self { 1 as $m } })*}
}
impl_OneTrait! {u8, u16, u32, u64, i8, i16, i32, i64}
/// This function either increments or decrements its argument, depending on the `INC` value.
/// If `true`, it increments; otherwise it decrements the argument.
fn increment_decrement<const INC: bool, T: OneTrait + SubAssign + AddAssign>(
mut val: T,
) -> T {
if INC {
val.add_assign(T::one());
} else {
val.sub_assign(T::one());
}
val
}
macro_rules! check_infinite_bounds {
($value:expr, $val:expr, $type:ident, $inc:expr) => {
if ($val == $type::MAX && $inc) || ($val == $type::MIN && !$inc) {
return $value;
}
};
}
/// This function returns the next/previous value depending on the `ADD` value.
/// If `true`, it returns the next value; otherwise it returns the previous value.
fn next_value<const INC: bool>(value: ScalarValue) -> ScalarValue {
use ScalarValue::*;
match value {
Float32(Some(val)) => {
let new_float = if INC { next_up(val) } else { next_down(val) };
Float32(Some(new_float))
}
Float64(Some(val)) => {
let new_float = if INC { next_up(val) } else { next_down(val) };
Float64(Some(new_float))
}
Int8(Some(val)) => {
check_infinite_bounds!(value, val, i8, INC);
Int8(Some(increment_decrement::<INC, i8>(val)))
}
Int16(Some(val)) => {
check_infinite_bounds!(value, val, i16, INC);
Int16(Some(increment_decrement::<INC, i16>(val)))
}
Int32(Some(val)) => {
check_infinite_bounds!(value, val, i32, INC);
Int32(Some(increment_decrement::<INC, i32>(val)))
}
Int64(Some(val)) => {
check_infinite_bounds!(value, val, i64, INC);
Int64(Some(increment_decrement::<INC, i64>(val)))
}
UInt8(Some(val)) => {
check_infinite_bounds!(value, val, u8, INC);
UInt8(Some(increment_decrement::<INC, u8>(val)))
}
UInt16(Some(val)) => {
check_infinite_bounds!(value, val, u16, INC);
UInt16(Some(increment_decrement::<INC, u16>(val)))
}
UInt32(Some(val)) => {
check_infinite_bounds!(value, val, u32, INC);
UInt32(Some(increment_decrement::<INC, u32>(val)))
}
UInt64(Some(val)) => {
check_infinite_bounds!(value, val, u64, INC);
UInt64(Some(increment_decrement::<INC, u64>(val)))
}
_ => value, // Unsupported datatypes
}
}
/// This function computes the selectivity of an operation by computing the
/// cardinality ratio of the given input/output intervals. If this can not be
/// calculated for some reason, it returns `1.0` meaning fullly selective (no
/// filtering).
pub fn cardinality_ratio(
initial_interval: &Interval,
final_interval: &Interval,
) -> Result<f64> {
Ok(
match (
final_interval.cardinality()?,
initial_interval.cardinality()?,
) {
(Some(final_interval), Some(initial_interval)) => {
final_interval as f64 / initial_interval as f64
}
_ => 1.0,
},
)
}
pub fn apply_operator(op: &Operator, lhs: &Interval, rhs: &Interval) -> Result<Interval> {
match *op {
Operator::Eq => Ok(lhs.equal(rhs)),
Operator::NotEq => Ok(lhs.equal(rhs).not()?),
Operator::Gt => Ok(lhs.gt(rhs)),
Operator::GtEq => Ok(lhs.gt_eq(rhs)),
Operator::Lt => Ok(lhs.lt(rhs)),
Operator::LtEq => Ok(lhs.lt_eq(rhs)),
Operator::And => lhs.and(rhs),
Operator::Or => lhs.or(rhs),
Operator::Plus => lhs.add(rhs),
Operator::Minus => lhs.sub(rhs),
_ => Ok(Interval::default()),
}
}
/// Cast scalar value to the given data type using an arrow kernel.
fn cast_scalar_value(
value: &ScalarValue,
data_type: &DataType,
cast_options: &CastOptions,
) -> Result<ScalarValue> {
let cast_array = cast_with_options(&value.to_array(), data_type, cast_options)?;
ScalarValue::try_from_array(&cast_array, 0)
}
/// This function calculates the final cardinality result by inspecting the endpoints of the interval.
fn calculate_cardinality_based_on_bounds(
lower_open: bool,
upper_open: bool,
diff: u64,
) -> u64 {
match (lower_open, upper_open) {
(false, false) => diff + 1,
(true, true) => diff - 1,
_ => diff,
}
}
/// An [Interval] that also tracks null status using a boolean interval.
///
/// This represents values that may be in a particular range or be null.
///
/// # Examples
///
/// ```
/// use arrow::datatypes::DataType;
/// use datafusion_physical_expr::intervals::{Interval, NullableInterval};
/// use datafusion_common::ScalarValue;
///
/// // [1, 2) U {NULL}
/// NullableInterval::MaybeNull {
/// values: Interval::make(Some(1), Some(2), (false, true)),
/// };
///
/// // (0, ∞)
/// NullableInterval::NotNull {
/// values: Interval::make(Some(0), None, (true, true)),
/// };
///
/// // {NULL}
/// NullableInterval::Null { datatype: DataType::Int32 };
///
/// // {4}
/// NullableInterval::from(ScalarValue::Int32(Some(4)));
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NullableInterval {
/// The value is always null in this interval
///
/// This is typed so it can be used in physical expressions, which don't do
/// type coercion.
Null { datatype: DataType },
/// The value may or may not be null in this interval. If it is non null its value is within
/// the specified values interval
MaybeNull { values: Interval },
/// The value is definitely not null in this interval and is within values
NotNull { values: Interval },
}
impl Default for NullableInterval {
fn default() -> Self {
NullableInterval::MaybeNull {
values: Interval::default(),
}
}
}
impl Display for NullableInterval {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::Null { .. } => write!(f, "NullableInterval: {{NULL}}"),
Self::MaybeNull { values } => {
write!(f, "NullableInterval: {} U {{NULL}}", values)
}
Self::NotNull { values } => write!(f, "NullableInterval: {}", values),
}
}
}
impl From<ScalarValue> for NullableInterval {
/// Create an interval that represents a single value.
fn from(value: ScalarValue) -> Self {
if value.is_null() {
Self::Null {
datatype: value.data_type(),
}
} else {
Self::NotNull {
values: Interval::new(
IntervalBound::new(value.clone(), false),
IntervalBound::new(value, false),
),
}
}
}
}
impl NullableInterval {
/// Get the values interval, or None if this interval is definitely null.
pub fn values(&self) -> Option<&Interval> {
match self {
Self::Null { .. } => None,
Self::MaybeNull { values } | Self::NotNull { values } => Some(values),
}
}
/// Get the data type
pub fn get_datatype(&self) -> Result<DataType> {
match self {
Self::Null { datatype } => Ok(datatype.clone()),
Self::MaybeNull { values } | Self::NotNull { values } => {
values.get_datatype()
}
}
}
/// Return true if the value is definitely true (and not null).
pub fn is_certainly_true(&self) -> bool {
match self {
Self::Null { .. } | Self::MaybeNull { .. } => false,
Self::NotNull { values } => values == &Interval::CERTAINLY_TRUE,
}
}
/// Return true if the value is definitely false (and not null).
pub fn is_certainly_false(&self) -> bool {
match self {
Self::Null { .. } => false,
Self::MaybeNull { .. } => false,
Self::NotNull { values } => values == &Interval::CERTAINLY_FALSE,
}
}
/// Perform logical negation on a boolean nullable interval.
fn not(&self) -> Result<Self> {
match self {
Self::Null { datatype } => Ok(Self::Null {
datatype: datatype.clone(),
}),
Self::MaybeNull { values } => Ok(Self::MaybeNull {
values: values.not()?,
}),
Self::NotNull { values } => Ok(Self::NotNull {
values: values.not()?,
}),
}
}
/// Apply the given operator to this interval and the given interval.
///
/// # Examples
///
/// ```
/// use datafusion_common::ScalarValue;
/// use datafusion_expr::Operator;
/// use datafusion_physical_expr::intervals::{Interval, NullableInterval};
///
/// // 4 > 3 -> true
/// let lhs = NullableInterval::from(ScalarValue::Int32(Some(4)));
/// let rhs = NullableInterval::from(ScalarValue::Int32(Some(3)));
/// let result = lhs.apply_operator(&Operator::Gt, &rhs).unwrap();
/// assert_eq!(result, NullableInterval::from(ScalarValue::Boolean(Some(true))));
///
/// // [1, 3) > NULL -> NULL
/// let lhs = NullableInterval::NotNull {
/// values: Interval::make(Some(1), Some(3), (false, true)),
/// };
/// let rhs = NullableInterval::from(ScalarValue::Int32(None));
/// let result = lhs.apply_operator(&Operator::Gt, &rhs).unwrap();
/// assert_eq!(result.single_value(), Some(ScalarValue::Boolean(None)));
///
/// // [1, 3] > [2, 4] -> [false, true]
/// let lhs = NullableInterval::NotNull {
/// values: Interval::make(Some(1), Some(3), (false, false)),
/// };
/// let rhs = NullableInterval::NotNull {
/// values: Interval::make(Some(2), Some(4), (false, false)),
/// };
/// let result = lhs.apply_operator(&Operator::Gt, &rhs).unwrap();
/// // Both inputs are valid (non-null), so result must be non-null
/// assert_eq!(result, NullableInterval::NotNull {
/// // Uncertain whether inequality is true or false
/// values: Interval::UNCERTAIN,
/// });
///
/// ```
pub fn apply_operator(&self, op: &Operator, rhs: &Self) -> Result<Self> {
match op {
Operator::IsDistinctFrom => {
let values = match (self, rhs) {
// NULL is distinct from NULL -> False
(Self::Null { .. }, Self::Null { .. }) => Interval::CERTAINLY_FALSE,
// x is distinct from y -> x != y,
// if at least one of them is never null.
(Self::NotNull { .. }, _) | (_, Self::NotNull { .. }) => {
let lhs_values = self.values();
let rhs_values = rhs.values();
match (lhs_values, rhs_values) {
(Some(lhs_values), Some(rhs_values)) => {
lhs_values.equal(rhs_values).not()?
}
(Some(_), None) | (None, Some(_)) => Interval::CERTAINLY_TRUE,
(None, None) => unreachable!("Null case handled above"),
}
}
_ => Interval::UNCERTAIN,
};
// IsDistinctFrom never returns null.
Ok(Self::NotNull { values })
}
Operator::IsNotDistinctFrom => self
.apply_operator(&Operator::IsDistinctFrom, rhs)
.map(|i| i.not())?,
_ => {
if let (Some(left_values), Some(right_values)) =
(self.values(), rhs.values())
{
let values = apply_operator(op, left_values, right_values)?;
match (self, rhs) {
(Self::NotNull { .. }, Self::NotNull { .. }) => {
Ok(Self::NotNull { values })