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
use super::def::{Interval, ParseIntervalError, SignClass};

use fp::{Float, Sign};

use std::fmt;
use std::fmt::{Display, Formatter, Write};
use std::str::FromStr;

impl SignClass {
    /// Whether `self` is `SignClass::Positive(_)`.
    pub fn is_positive(&self) -> bool {
        match *self {
            SignClass::Positive(_) => true,
            _ => false,
        }
    }

    /// Whether `self` is `SignClass::Negative(_)`.
    pub fn is_negative(&self) -> bool {
        match *self {
            SignClass::Negative(_) => true,
            _ => false,
        }
    }
}

impl Display for SignClass {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        match *self {
            SignClass::Mixed => f.write_str("m"),
            SignClass::Zero => f.write_str("z"),
            SignClass::Positive(has_zero) => if has_zero {
                f.write_str("p0")
            } else {
                f.write_str("p1")
            },
            SignClass::Negative(has_zero) => if has_zero {
                f.write_str("n0")
            } else {
                f.write_str("n1")
            },
        }
    }
}

impl<BOUND: Float> Interval<BOUND> {
    /// Constructs a new interval from given bounds.
    ///
    /// Lower bound must be less than or equal to upper bound. Only exception is when they are both
    /// NaNs, in which case a NaN (empty) interval is created.
    ///
    /// Cases where both bounds are negative infinity or positive infinity are not allowed as these
    /// are empty sets. If you want to represent an empty set, use `Interval::nan()`.
    #[inline]
    pub fn new(lo: BOUND, hi: BOUND) -> Self {
        assert_eq!(lo.precision(), hi.precision(),
                   "inconsistent precision: {} != {}", lo.precision(), hi.precision());
        assert!(!lo.is_nan() && !hi.is_nan() && lo <= hi || lo.is_nan() && hi.is_nan(),
                "invalid bounds: <{}, {}>", lo, hi);
        assert!(!(lo.is_infinity() && hi.is_infinity()) && !(lo.is_neg_infinity() && hi.is_neg_infinity()),
                "invalid bounds: <{}, {}>", lo, hi);
        Interval { lo: lo, hi: hi }
    }

    /// Constructs the minimal interval that covers all of the given intervals.
    pub fn minimal_cover(mut intervals: Vec<Self>, precision: usize) -> Self {
        intervals.retain(|i| !i.is_nan());
        if intervals.is_empty() {
            return Self::nan(precision)
        }
        let lo = intervals.iter()
            .map(|i| i.lo.clone())
            .fold(BOUND::infinity(precision), |x, y| x.min(y));
        let hi = intervals.iter()
            .map(|i| i.hi.clone())
            .fold(BOUND::neg_infinity(precision), |x, y| x.max(y));
        Self { lo: lo, hi: hi }
    }

    /// Constructs a singleton interval (an interval with only one element).
    #[inline]
    pub fn singleton(val: BOUND) -> Self {
        Self::new(val.clone(), val)
    }

    /// Constructs an interval that contains only zero.
    #[inline]
    pub fn zero(precision: usize) -> Self {
        Self::new(BOUND::zero(precision), BOUND::zero(precision))
    }

    /// Constructs an interval that contains only one.
    #[inline]
    pub fn one(precision: usize) -> Self {
        Self::new(BOUND::one(precision), BOUND::one(precision))
    }

    /// Constructs a NaN (empty) interval.
    #[inline]
    pub fn nan(precision: usize) -> Self {
        Self::new(BOUND::nan(precision), BOUND::nan(precision))
    }

    /// Constructs an interval that contains all numbers.
    #[inline]
    pub fn whole(precision: usize) -> Self {
        Self::new(BOUND::neg_infinity(precision), BOUND::infinity(precision))
    }

    /// Constructs an interval from a float with given precision.
    #[inline]
    pub fn from_with_prec(val: f64, precision: usize) -> Self {
        Self::new(BOUND::from_lo(val, precision), BOUND::from_hi(val, precision))
    }

    /// Constructs an interval by parsing a string.
    ///
    /// Accepts `INTERVAL` according to the rule below.
    ///
    ///   INTERVAL = FLOAT | '<' FLOAT ',' FLOAT '>'
    pub fn from_str_with_prec(s: &str, precision: usize) -> Result<Self, ParseIntervalError> {
        let lo = BOUND::from_str_lo(s, precision);
        let hi = BOUND::from_str_hi(s, precision);
        if let (Ok(lo), Ok(hi)) = (lo, hi) {
            Ok(Self::new(lo, hi))
        } else {
            if !s.starts_with('<') { return Err(ParseIntervalError::MissingOpeningBracket) }
            let s = s.trim_left_matches('<').trim_left();
            if !s.ends_with('>') { return Err(ParseIntervalError::MissingClosingBracket) }
            let s = s.trim_right_matches('>').trim_right();
            let p: Vec<&str> = s.split(',').collect();
            if p.len() == 2 {
                let lo = BOUND::from_str_lo(p[0].trim(), precision);
                let hi = BOUND::from_str_hi(p[1].trim(), precision);
                if let (Ok(lo), Ok(hi)) = (lo, hi) {
                    if !lo.is_nan() && !hi.is_nan() && lo <= hi || lo.is_nan() && hi.is_nan() {
                        Ok(Self::new(lo, hi))
                    } else {
                        Err(ParseIntervalError::InvalidBounds)
                    }
                } else {
                    Err(ParseIntervalError::BoundsParseError)
                }
            } else {
                Err(ParseIntervalError::InvalidNumberOfBounds)
            }
        }
    }

    /// Returns the sign class of `self`.
    #[inline]
    pub fn sign_class(&self) -> SignClass {
        match self.lo.sign() {
            Sign::Negative => match self.hi.sign() {
                Sign::Negative => SignClass::Negative(false),
                Sign::Zero => SignClass::Negative(true),
                Sign::Positive => SignClass::Mixed,
            },
            Sign::Zero => match self.hi.sign() {
                Sign::Negative => unreachable!(),
                Sign::Zero => SignClass::Zero,
                Sign::Positive => SignClass::Positive(true),
            },
            Sign::Positive => match self.hi.sign() {
                Sign::Negative => unreachable!(),
                Sign::Zero => unreachable!(),
                Sign::Positive => SignClass::Positive(false),
            },
        }
    }

    /// Returns the precision of `self`.
    #[inline]
    pub fn precision(&self) -> usize {
        assert!(self.lo.precision() == self.hi.precision());
        self.lo.precision()
    }

    /// Returns the difference between the upper bound and the lower bound of `self`.
    ///
    /// As the result is not always exactly representable as `BOUND`, an interval is returned
    /// instead.
    #[inline]
    pub fn size(&self) -> Self {
        if self.is_whole() {
            Self::nan(self.precision())
        } else {
            Self::singleton(self.hi.clone()) - Self::singleton(self.lo.clone())
        }
    }

    /// Whether `self` is a singleton interval (an interval containing only one element).
    #[inline]
    pub fn is_singleton(&self) -> bool {
        self.lo == self.hi
    }

    /// Whether `self` contains only zero.
    #[inline]
    pub fn is_zero(&self) -> bool {
        self.lo.sign() == Sign::Zero && self.hi.sign() == Sign::Zero && !self.is_nan()
    }

    /// Whether `self` is NaN (empty).
    #[inline]
    pub fn is_nan(&self) -> bool {
        assert!(self.lo.is_nan() == self.hi.is_nan());
        self.lo.is_nan()
    }

    /// Whether `self` contains all numbers.
    #[inline]
    pub fn is_whole(&self) -> bool {
        self.lo.is_neg_infinity() && self.hi.is_infinity()
    }

    /// Whether `self` contains zero.
    #[inline]
    pub fn has_zero(&self) -> bool {
        self.lo.sign() <= Sign::Zero && self.hi.sign() >= Sign::Zero
    }

    /// Cuts `self` into two at `val` and returns the left and right pieces as a pair.
    ///
    /// If `self` lies on only one side of `val`, the non-existent side will be a NaN interval.
    #[inline]
    pub fn split(self, val: BOUND) -> (Self, Self) {
        let precision = self.precision();
        if self.lo >= val {
            (Self::nan(precision), self)
        } else if self.hi <= val {
            (self, Self::nan(precision))
        } else {
            if self.is_nan() {
                let precision = self.precision();
                (Self::nan(precision), Self::nan(precision))
            } else {
                (Self::new(self.lo, val.clone()), Self::new(val, self.hi))
            }
        }
    }
}

impl<BOUND: Float> From<f64> for Interval<BOUND> {
    #[inline]
    fn from(val: f64) -> Self {
        Self::from_with_prec(val, 53)
    }
}

impl<BOUND: Float> FromStr for Interval<BOUND> {
    type Err = ParseIntervalError;

    #[inline]
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::from_str_with_prec(s, 53)
    }
}

impl<BOUND: Float> Display for Interval<BOUND> {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        if self.is_singleton() || self.is_nan() {
            Display::fmt(&self.lo, f)
        } else {
            if let Err(e) = f.write_char('<') { return Err(e) }
            if let Err(e) = Display::fmt(&self.lo, f) { return Err(e) }
            if let Err(e) = f.write_str(", ") { return Err(e) }
            if let Err(e) = Display::fmt(&self.hi, f) { return Err(e) }
            f.write_char('>')
        }
    }
}

impl<BOUND: Float> Into<(BOUND, BOUND)> for Interval<BOUND> {
    fn into(self) -> (BOUND, BOUND) {
        (self.lo, self.hi)
    }
}