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
use serde_json::json;
use std::default::Default;
use std::fmt::{self, Display, Formatter};
use std::ops::{Add, AddAssign, BitAnd, BitAndAssign, Neg, Sub, SubAssign};
use wasm_bindgen::prelude::*;

/// An interval represents a context-agnostic inclusive [lower, upper] time range. While Interval may be accessible from JS, the Rust implementation includes additional operator overloads for simplified arithmetic.
///
/// # JS-specific
///
/// * Use `.toJSON()` if you want to convert an `Interval` to an array of numbers
/// * Using indexing to get the lower and upper bounds is also an option, eg. `interval[0] === lower && interval[1] === upper`
/// * use `Number.MAX_VALUE` and `-Number.MAX_VALUE` to represent infinity and -infinity respectively
///
/// # Examples
///
/// Interval arithmetic in Rust.
///
/// ```
/// use temporal_networks::interval::Interval;
///
/// let interval1 = Interval::new(0., 10.);
/// let interval2 = Interval::new(5., 16.);
///
/// let summed_interval = Interval::new(5., 26.);
/// assert_eq!(interval1 + interval2, summed_interval);
///
/// let diff_interval = Interval::new(-5., 16.);
/// assert_eq!(interval2 - interval1, diff_interval);
///
/// let unioned_interval = Interval::new(5., 10.);
/// assert_eq!(interval1 & interval2, unioned_interval);
/// ```
#[wasm_bindgen]
#[derive(Deserialize, Serialize, Copy, Clone, Debug, PartialEq, Default)]
pub struct Interval(pub f64, pub f64);

#[wasm_bindgen]
impl Interval {
    /// Create a new Interval
    #[wasm_bindgen(constructor)]
    pub fn new(lower: f64, upper: f64) -> Interval {
        Interval(lower, upper)
    }

    /// Get an interval from a vector
    pub fn from_vec(other: Vec<f64>) -> Interval {
        Interval::new(other[0], other[1])
    }

    /// Convert the interval to JSON `[lower, upper]`
    #[wasm_bindgen(js_name = toJSON)]
    pub fn to_json(&self) -> JsValue {
        let value = json!([self.0, self.1]);
        JsValue::from_serde(&value).unwrap()
    }

    /// The lower bound of the range
    #[wasm_bindgen]
    pub fn lower(&self) -> f64 {
        self.0
    }

    /// The upper bound of the range
    #[wasm_bindgen]
    pub fn upper(&self) -> f64 {
        self.1
    }

    /// Whether or not a point in time falls within a range
    #[wasm_bindgen]
    pub fn contains(&self, v: f64) -> bool {
        v >= self.lower() && v <= self.upper()
    }

    /// A check that ensures the lower bound is less than the upper bound
    #[wasm_bindgen(js_name = isValid)]
    pub fn is_valid(&self) -> bool {
        self.lower() <= self.upper()
    }

    /// Whether or not the interval has converged to a time
    #[wasm_bindgen]
    pub fn converged(&self) -> bool {
        (self.0 - self.1).abs() < 0.001
    }

    /// Union these intervals
    #[wasm_bindgen]
    pub fn union(&self, other: &Interval) -> Interval {
        *self & *other
    }
}

impl Display for Interval {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        // `f` is a buffer, and this method must write the formatted string into it
        // `write!` is like `format!`, but it will write the formatted string
        // into a buffer (the first argument)
        write!(f, "[{}, {}]", self.0, self.1)
    }
}

impl Add for Interval {
    type Output = Interval;

    /// create a new interval from the addition of two other intervals
    fn add(self, other: Interval) -> Interval {
        Interval(self.0 + other.0, self.1 + other.1)
    }
}

// [l_1, u_1] += [l_2, u_2] == [l_1 + l_2, u_1 + u_2]
impl AddAssign for Interval {
    fn add_assign(&mut self, other: Interval) {
        *self = Interval(self.0 + other.0, self.1 + other.1)
    }
}

// -[l_1, u_1] = [-u_1, -l_1]
impl Neg for Interval {
    type Output = Interval;

    fn neg(self) -> Interval {
        Interval(-self.1, -self.0)
    }
}

// [l_1, u_1] - [l_2, u_2] = [l_1, u_1] + [-u_2, -l_2] = [l_1 - u_2, u_1 - l_2]
impl Sub for Interval {
    type Output = Interval;

    fn sub(self, other: Interval) -> Interval {
        self + -other
    }
}

// [l_1, u_1] -= [l_2, u_2] = [l_1, u_1] + [-u_2, -l_2] = [l_1 - u_2, u_1 - l_2]
impl SubAssign for Interval {
    fn sub_assign(&mut self, other: Interval) {
        *self += -other
    }
}

// l_1, u_1] & [l_2, u_2] = [\max(l_1, l_2), \min(u_1, u_2)]
impl BitAnd for Interval {
    type Output = Interval;

    fn bitand(self, other: Interval) -> Interval {
        Interval(self.0.max(other.0), self.1.min(other.1))
    }
}

// l_1, u_1] &= [l_2, u_2] = [\max(l_1, l_2), \min(u_1, u_2)]
impl BitAndAssign for Interval {
    fn bitand_assign(&mut self, other: Interval) {
        *self = Interval(self.0.max(other.0), self.1.min(other.1))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_interval_add() {
        struct Case {
            in1: Interval,
            in2: Interval,
            out: Interval,
        }

        let cases = vec![
            Case {
                in1: Interval(1., 1.),
                in2: Interval(2., 2.),
                out: Interval(3., 3.),
            },
            Case {
                in1: Interval(0., 0.),
                in2: Interval(2., 2.),
                out: Interval(2., 2.),
            },
            Case {
                in1: Interval(1.5, 1.5),
                in2: Interval(2., 2.),
                out: Interval(3.5, 3.5),
            },
        ];

        for case in cases.iter() {
            let res = case.in1 + case.in2;

            assert_eq!(case.out, res, "{} + {} == {}", case.in1, case.in2, case.out);
        }
    }

    #[test]
    fn test_interval_add_assign() {
        struct Case {
            in1: Interval,
            in2: Interval,
            out: Interval,
        }

        let mut cases = vec![
            Case {
                in1: Interval(1., 1.),
                in2: Interval(2., 2.),
                out: Interval(3., 3.),
            },
            Case {
                in1: Interval(0., 0.),
                in2: Interval(2., 2.),
                out: Interval(2., 2.),
            },
            Case {
                in1: Interval(1.5, 1.5),
                in2: Interval(2., 2.),
                out: Interval(3.5, 3.5),
            },
        ];

        for case in cases.iter_mut() {
            case.in1 += case.in2;

            assert_eq!(
                case.out, case.in1,
                "{} += {} == {}",
                case.in1, case.in2, case.out
            );
        }
    }

    #[test]
    fn test_interval_sub() {
        struct Case {
            in1: Interval,
            in2: Interval,
            out: Interval,
        }

        let cases = vec![
            Case {
                in1: Interval(2., 2.),
                in2: Interval(1., 1.),
                out: Interval(1., 1.),
            },
            Case {
                in1: Interval(8., 12.),
                in2: Interval(4., 6.),
                out: Interval(2., 8.),
            },
            Case {
                in1: Interval(2., 2.),
                in2: Interval(1.5, 1.5),
                out: Interval(0.5, 0.5),
            },
        ];

        for case in cases.iter() {
            let res = case.in1 - case.in2;

            assert_eq!(case.out, res, "{} - {} == {}", case.in1, case.in2, case.out);
        }
    }

    #[test]
    fn test_interval_sub_assign() {
        struct Case {
            in1: Interval,
            in2: Interval,
            out: Interval,
        }

        let mut cases = vec![
            Case {
                in1: Interval(2., 2.),
                in2: Interval(1., 1.),
                out: Interval(1., 1.),
            },
            Case {
                in1: Interval(8., 12.),
                in2: Interval(4., 6.),
                out: Interval(2., 8.),
            },
            Case {
                in1: Interval(2., 2.),
                in2: Interval(1.5, 1.5),
                out: Interval(0.5, 0.5),
            },
        ];

        for case in cases.iter_mut() {
            case.in1 -= case.in2;

            assert_eq!(
                case.out, case.in1,
                "{} -= {} == {}",
                case.in1, case.in2, case.out
            );
        }
    }

    #[test]
    fn test_interval_union() {
        struct Case {
            in1: Interval,
            in2: Interval,
            out: Interval,
        }

        let cases = vec![
            Case {
                in1: Interval(1., 3.),
                in2: Interval(2., 4.),
                out: Interval(2., 3.),
            },
            Case {
                in1: Interval(0., 10.1),
                in2: Interval(1., 12.),
                out: Interval(1., 10.1),
            },
        ];

        for case in cases.iter() {
            let res = case.in1 & case.in2;

            assert_eq!(case.out, res, "{} ^ {} == {}", case.in1, case.in2, case.out);
        }
    }

    #[test]
    fn test_interval_union_assign() {
        struct Case {
            in1: Interval,
            in2: Interval,
            out: Interval,
        }

        let mut cases = vec![
            Case {
                in1: Interval(1., 3.),
                in2: Interval(2., 4.),
                out: Interval(2., 3.),
            },
            Case {
                in1: Interval(0., 10.1),
                in2: Interval(1., 12.),
                out: Interval(1., 10.1),
            },
        ];

        for case in cases.iter_mut() {
            case.in1 &= case.in2;

            assert_eq!(
                case.out, case.in1,
                "{} ^= {} == {}",
                case.in1, case.in2, case.out
            );
        }
    }

    #[test]
    fn test_mixed_operators() {
        let i1 = Interval::new(40., 50.);
        let i2 = Interval::new(15., 15.);
        let i3 = Interval::new(30., 40.);

        let res = i1 & (i2 + i3);
        assert_eq!(
            res,
            Interval::new(45., 50.),
            "interval math from scheduling walkthrough"
        );
    }
}