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
use std::fmt;

use macros::ElementwiseComparator;
use macros::comparison::ComparisonFailure;


#[doc(hidden)]
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct ScalarComparisonFailure<T, E> where E: ComparisonFailure {
    pub x: T,
    pub y: T,
    pub error: E
}

impl<T, E> fmt::Display for ScalarComparisonFailure<T, E>
    where T: fmt::Display, E: ComparisonFailure {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f,
               "x = {x}, y = {y}.{reason}",
               x = self.x,
               y = self.y,
               reason = self.error.failure_reason()
                                  // Add a space before the reason
                                  .map(|s| format!(" {}", s))
                                  .unwrap_or(String::new()))
    }
}

#[doc(hidden)]
#[derive(Debug, PartialEq)]
pub enum ScalarComparisonResult<T, C, E>
    where T: Copy,
          C: ElementwiseComparator<T, E>,
          E: ComparisonFailure
{
    Match,
    Mismatch {
        comparator: C,
        mismatch: ScalarComparisonFailure<T, E>
    }
}

impl <T, C, E> ScalarComparisonResult<T, C, E>
    where T: Copy + fmt::Display, C: ElementwiseComparator<T, E>, E: ComparisonFailure {
    pub fn panic_message(&self) -> Option<String> {
        match self {
            &ScalarComparisonResult::Mismatch { ref comparator, ref mismatch } => {
                Some(format!("\n
Scalars x and y do not compare equal.

{mismatch}

Comparison criterion: {description}
\n",
                    description = comparator.description(),
                    mismatch = mismatch.to_string()
                ))
            },
            _ => None
        }
    }
}

#[doc(hidden)]
pub fn scalar_comparison<T, C, E>(x: T, y: T, comparator: C)
    -> ScalarComparisonResult<T, C, E>
    where T: Copy,
          C: ElementwiseComparator<T, E>,
          E: ComparisonFailure {

    match comparator.compare(x, y) {
        Err(error) => ScalarComparisonResult::Mismatch {
            comparator: comparator,
            mismatch: ScalarComparisonFailure {
                x: x,
                y: y,
                error: error
            }
        },
        _ => ScalarComparisonResult::Match
    }
}

/// Compare scalars for exact or approximate equality.
///
/// This macro works analogously to [assert_matrix_eq!](macro.assert_matrix_eq.html),
/// but is used for comparing scalars (e.g. integers, floating-point numbers)
/// rather than matrices. Please see the documentation for `assert_matrix_eq!`
/// for details about issues that arise when comparing floating-point numbers,
/// as well as an explanation for how these macros can be used to resolve
/// these issues.
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate rulinalg; fn main() {
/// let x = 3.00;
/// let y = 3.05;
/// // Assert that |x - y| <= 0.1
/// assert_scalar_eq!(x, y, comp = abs, tol = 0.1);
/// # }
/// ```
#[macro_export]
macro_rules! assert_scalar_eq {
    ($x:expr, $y:expr) => {
        {
            use $crate::macros::{scalar_comparison, ExactElementwiseComparator};
            let comp = ExactElementwiseComparator;
            let msg = scalar_comparison($x.clone(), $y.clone(), comp).panic_message();
            if let Some(msg) = msg {
                // Note: We need the panic to incur here inside of the macro in order
                // for the line number to be correct when using it for tests,
                // hence we build the panic message in code, but panic here.
                panic!("{msg}
Please see the documentation for ways to compare scalars approximately.\n\n",
                    msg = msg.trim_right());
            }
        }
    };
    ($x:expr, $y:expr, comp = exact) => {
        {
            use $crate::macros::{scalar_comparison, ExactElementwiseComparator};
            let comp = ExactElementwiseComparator;
            let msg = scalar_comparison($x.clone(), $y.clone(), comp).panic_message();
            if let Some(msg) = msg {
                panic!(msg);
            }
        }
    };
    ($x:expr, $y:expr, comp = abs, tol = $tol:expr) => {
        {
            use $crate::macros::{scalar_comparison, AbsoluteElementwiseComparator};
            let comp = AbsoluteElementwiseComparator { tol: $tol };
            let msg = scalar_comparison($x.clone(), $y.clone(), comp).panic_message();
            if let Some(msg) = msg {
                panic!(msg);
            }
        }
    };
    ($x:expr, $y:expr, comp = ulp, tol = $tol:expr) => {
        {
            use $crate::macros::{scalar_comparison, UlpElementwiseComparator};
            let comp = UlpElementwiseComparator { tol: $tol };
            let msg = scalar_comparison($x.clone(), $y.clone(), comp).panic_message();
            if let Some(msg) = msg {
                panic!(msg);
            }
        }
    };
    ($x:expr, $y:expr, comp = float) => {
        {
            use $crate::macros::{scalar_comparison, FloatElementwiseComparator};
            let comp = FloatElementwiseComparator::default();
            let msg = scalar_comparison($x.clone(), $y.clone(), comp).panic_message();
            if let Some(msg) = msg {
                panic!(msg);
            }
        }
    };
    // The following allows us to optionally tweak the epsilon and ulp tolerances
    // used in the default float comparator.
    ($x:expr, $y:expr, comp = float, $($key:ident = $val:expr),+) => {
        {
            use $crate::macros::{scalar_comparison, FloatElementwiseComparator};
            let comp = FloatElementwiseComparator::default()$(.$key($val))+;
            let msg = scalar_comparison($x.clone(), $y.clone(), comp).panic_message();
            if let Some(msg) = msg {
                panic!(msg);
            }
        }
    };
}

#[cfg(test)]
mod tests {
    use super::scalar_comparison;
    use macros::comparison::{
        ExactElementwiseComparator, ExactError
    };

    #[test]
    fn scalar_comparison_reports_correct_mismatch() {
        use super::ScalarComparisonResult::Mismatch;
        use super::ScalarComparisonFailure;

        let comp = ExactElementwiseComparator;

        {
            let x = 0.2;
            let y = 0.3;

            let expected = Mismatch {
                comparator: comp,
                mismatch: ScalarComparisonFailure {
                    x: 0.2, y: 0.3,
                    error: ExactError
                }
            };

            assert_eq!(scalar_comparison(x, y, comp), expected);
        }
    }

    #[test]
    pub fn scalar_eq_default_compare_self_for_integer() {
        let x = 2;
        assert_scalar_eq!(x, x);
    }

    #[test]
    pub fn scalar_eq_default_compare_self_for_floating_point() {
        let x = 2.0;
        assert_scalar_eq!(x, x);
    }

    #[test]
    #[should_panic]
    pub fn scalar_eq_default_mismatched_elements() {
        let x = 3;
        let y = 4;
        assert_scalar_eq!(x, y);
    }

    #[test]
    pub fn scalar_eq_exact_compare_self_for_integer() {
        let x = 2;
        assert_scalar_eq!(x, x, comp = exact);
    }

    #[test]
    pub fn scalar_eq_exact_compare_self_for_floating_point() {
        let x = 2.0;
        assert_scalar_eq!(x, x, comp = exact);;
    }

    #[test]
    #[should_panic]
    pub fn scalar_eq_exact_mismatched_elements() {
        let x = 3;
        let y = 4;
        assert_scalar_eq!(x, y, comp = exact);
    }

    #[test]
    pub fn scalar_eq_abs_compare_self_for_integer() {
        let x = 2;
        assert_scalar_eq!(x, x, comp = abs, tol = 1);
    }

    #[test]
    pub fn scalar_eq_abs_compare_self_for_floating_point() {
        let x = 2.0;
        assert_scalar_eq!(x, x, comp = abs, tol = 1e-8);
    }

    #[test]
    #[should_panic]
    pub fn scalar_eq_abs_mismatched_elements() {
        let x = 3.0;
        let y = 4.0;
        assert_scalar_eq!(x, y, comp = abs, tol = 1e-8);
    }

    #[test]
    pub fn scalar_eq_ulp_compare_self() {
        let x = 2.0;
        assert_scalar_eq!(x, x, comp = ulp, tol = 1);
    }

    #[test]
    #[should_panic]
    pub fn scalar_eq_ulp_mismatched_elements() {
        let x = 3.0;
        let y = 4.0;
        assert_scalar_eq!(x, y, comp = ulp, tol = 4);
    }

    #[test]
    pub fn scalar_eq_float_compare_self() {
        let x = 2.0;
        assert_scalar_eq!(x, x, comp = ulp, tol = 1);
    }

    #[test]
    #[should_panic]
    pub fn scalar_eq_float_mismatched_elements() {
        let x = 3.0;
        let y = 4.0;
        assert_scalar_eq!(x, y, comp = float);
    }

    #[test]
    pub fn scalar_eq_float_compare_self_with_eps() {
        let x = 2.0;
        assert_scalar_eq!(x, x, comp = float, eps = 1e-6);
    }

    #[test]
    pub fn scalar_eq_float_compare_self_with_ulp() {
        let x = 2.0;
        assert_scalar_eq!(x, x, comp = float, ulp = 12);
    }

    #[test]
    pub fn scalar_eq_float_compare_self_with_eps_and_ulp() {
        let x = 2.0;
        assert_scalar_eq!(x, x, comp = float, eps = 1e-6, ulp = 12);
        assert_scalar_eq!(x, x, comp = float, ulp = 12, eps = 1e-6);
    }

    #[test]
    pub fn scalar_eq_pass_by_ref()
    {
        let x = 0.0;

        // Exercise all the macro definitions and make sure that we are able to call it
        // when the arguments are references.
        assert_scalar_eq!(&x, &x);
        assert_scalar_eq!(&x, &x, comp = exact);
        assert_scalar_eq!(&x, &x, comp = abs, tol = 0.0);
        assert_scalar_eq!(&x, &x, comp = ulp, tol = 0);
        assert_scalar_eq!(&x, &x, comp = float);
        assert_scalar_eq!(&x, &x, comp = float, eps = 0.0, ulp = 0);
    }
}