qfall-math 0.1.1

Mathematical foundations for rapid prototyping of lattice-based cryptography
Documentation
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
// Copyright © 2023 Phil Milewski, Marcel Luca Schmidt
//
// This file is part of qFALL-math.
//
// qFALL-math is free software: you can redistribute it and/or modify it under
// the terms of the Mozilla Public License Version 2.0 as published by the
// Mozilla Foundation. See <https://mozilla.org/en-US/MPL/2.0/>.

//! Implementation of the [`Sub`] trait for [`MatQ`] values.

use super::super::MatQ;
use crate::error::MathError;
use crate::integer::MatZ;
use crate::macros::arithmetics::{
    arithmetic_assign_trait_borrowed_to_owned, arithmetic_trait_borrowed_to_owned,
    arithmetic_trait_mixed_borrowed_owned,
};
use crate::traits::MatrixDimensions;
use flint_sys::fmpq_mat::fmpq_mat_sub;
use std::ops::{Sub, SubAssign};

impl SubAssign<&MatQ> for MatQ {
    /// Computes the subtraction of `self` and `other` reusing
    /// the memory of `self`.
    /// [`SubAssign`] can be used on [`MatQ`] in combination with
    /// [`MatQ`] and [`MatZ`].
    ///
    /// Parameters:
    /// - `other`: specifies the value to subrract from `self`
    ///
    /// # Examples
    /// ```
    /// use qfall_math::{rational::MatQ, integer::MatZ};
    /// let mut a = MatQ::identity(2, 2);
    /// let b = MatQ::new(2, 2);
    /// let c = MatZ::new(2, 2);
    ///
    /// a -= &b;
    /// a -= b;
    /// a -= &c;
    /// a -= c;
    /// ```
    ///
    /// # Panics ...
    /// - if the matrix dimensions mismatch.
    fn sub_assign(&mut self, other: &Self) {
        if self.get_num_rows() != other.get_num_rows()
            || self.get_num_columns() != other.get_num_columns()
        {
            panic!(
                "Tried to subtract a '{}x{}' matrix and a '{}x{}' matrix.",
                self.get_num_rows(),
                self.get_num_columns(),
                other.get_num_rows(),
                other.get_num_columns()
            );
        }

        unsafe { fmpq_mat_sub(&mut self.matrix, &self.matrix, &other.matrix) };
    }
}
impl SubAssign<&MatZ> for MatQ {
    /// Documentation at [`MatQ::sub_assign`].
    fn sub_assign(&mut self, other: &MatZ) {
        if self.get_num_rows() != other.get_num_rows()
            || self.get_num_columns() != other.get_num_columns()
        {
            panic!(
                "Tried to subtract a '{}x{}' matrix and a '{}x{}' matrix.",
                self.get_num_rows(),
                self.get_num_columns(),
                other.get_num_rows(),
                other.get_num_columns()
            );
        }

        let other = MatQ::from(other);
        unsafe {
            fmpq_mat_sub(&mut self.matrix, &self.matrix, &other.matrix);
        }
    }
}

arithmetic_assign_trait_borrowed_to_owned!(SubAssign, sub_assign, MatQ, MatQ);
arithmetic_assign_trait_borrowed_to_owned!(SubAssign, sub_assign, MatQ, MatZ);

impl Sub for &MatQ {
    type Output = MatQ;
    /// Implements the [`Sub`] trait for two matrices.
    /// [`Sub`] is implemented for any combination of [`MatQ`] and borrowed [`MatQ`].
    ///
    /// Parameters:
    /// - `other`: specifies the value to subtract from `self`
    ///
    /// Returns the result of the subtraction as a [`MatQ`].
    ///
    /// # Examples
    /// ```
    /// use qfall_math::rational::MatQ;
    /// use std::str::FromStr;
    ///
    /// let a: MatQ = MatQ::from_str("[[1/2, 2/3, 3/4],[3/4, 4/5, 5/7]]").unwrap();
    /// let b: MatQ = MatQ::from_str("[[1/4, 9/7, 3/7],[1, 0, 5]]").unwrap();
    ///
    /// let d: MatQ = &a - &b;
    /// let e: MatQ = a - b;
    /// let f: MatQ = &d - e;
    /// let g: MatQ = d - &f;
    /// ```
    ///
    /// # Panics ...
    /// - if the dimensions of both matrices mismatch.
    fn sub(self, other: Self) -> Self::Output {
        self.sub_safe(other).unwrap()
    }
}

impl Sub<&MatZ> for &MatQ {
    type Output = MatQ;

    /// Implements the [`Sub`] trait for a [`MatQ`] and a [`MatZ`] matrix.
    /// [`Sub`] is implemented for any combination of owned and borrowed values.
    ///
    /// Parameters:
    /// - `other`: specifies the matrix to subtract from `self`.
    ///
    /// Returns the subtraction of `self` and `other` as a [`MatQ`].
    ///
    /// # Examples
    /// ```
    /// use qfall_math::{integer::MatZ, rational::MatQ};
    /// use std::str::FromStr;
    ///
    /// let a = MatZ::from_str("[[1, 2, 3],[3, 4, 5]]").unwrap();
    /// let b = MatQ::from_str("[[1/2, 9, 3/8],[1/7, 0, 5]]").unwrap();
    ///
    /// let c = &b - &a;
    /// let d = b.clone() - a.clone();
    /// let e = &b - &a;
    /// let f = b - a;
    /// ```
    ///
    /// # Panics ...
    /// - if the dimensions of both matrices mismatch.
    fn sub(self, other: &MatZ) -> Self::Output {
        let other = MatQ::from(other);

        self.sub_safe(&other).unwrap()
    }
}

arithmetic_trait_borrowed_to_owned!(Sub, sub, MatQ, MatZ, MatQ);
arithmetic_trait_mixed_borrowed_owned!(Sub, sub, MatQ, MatZ, MatQ);

impl MatQ {
    /// Implements subtraction for two [`MatQ`] matrices.
    ///
    ///
    /// Parameters:
    /// - `other`: specifies the value to subtract from`self`
    ///
    /// Returns the result of the subtraction as a [`MatQ`] or an
    /// error if the matrix dimensions mismatch.
    ///
    /// # Examples
    /// ```
    /// use qfall_math::rational::MatQ;
    /// use std::str::FromStr;
    ///
    /// let a: MatQ = MatQ::from_str("[[1/2, 2/3, 3/4],[3/4, 4/5, 5/7]]").unwrap();
    /// let b: MatQ = MatQ::from_str("[[1/4, 9/7, 3/7],[1, 0, 5]]").unwrap();
    ///
    /// let c: MatQ = a.sub_safe(&b).unwrap();
    /// ```
    /// # Errors
    /// - Returns a [`MathError`] of type
    ///   [`MathError::MismatchingMatrixDimension`] if the matrix dimensions
    ///   mismatch.
    pub fn sub_safe(&self, other: &Self) -> Result<MatQ, MathError> {
        if self.get_num_rows() != other.get_num_rows()
            || self.get_num_columns() != other.get_num_columns()
        {
            return Err(MathError::MismatchingMatrixDimension(format!(
                "Tried to subtract a '{}x{}' matrix and a '{}x{}' matrix.",
                other.get_num_rows(),
                other.get_num_columns(),
                self.get_num_rows(),
                self.get_num_columns()
            )));
        }
        let mut out = MatQ::new(self.get_num_rows(), self.get_num_columns());
        unsafe {
            fmpq_mat_sub(&mut out.matrix, &self.matrix, &other.matrix);
        }
        Ok(out)
    }
}

arithmetic_trait_borrowed_to_owned!(Sub, sub, MatQ, MatQ, MatQ);
arithmetic_trait_mixed_borrowed_owned!(Sub, sub, MatQ, MatQ, MatQ);

#[cfg(test)]
mod test_sub_assign {
    use crate::{integer::MatZ, rational::MatQ};
    use std::str::FromStr;

    /// Ensure that `sub_assign` works for small numbers.
    #[test]
    fn correct_small() {
        let mut a = MatQ::identity(2, 2);
        let b = MatQ::from_str("[[-4/5, -5],[6, 1]]").unwrap();
        let mut c = a.clone();
        let d = MatZ::from_str("[[-4, -5],[6, 1]]").unwrap();
        let cmp_0 = MatQ::from_str("[[9/5, 5],[-6, 0]]").unwrap();
        let cmp_1 = MatQ::from_str("[[5, 5],[-6, 0]]").unwrap();

        a -= b;
        c -= d;

        assert_eq!(cmp_0, a);
        assert_eq!(cmp_1, c);
    }

    /// Ensure that `sub_assign` works for large numbers.
    #[test]
    fn correct_large() {
        let mut a = MatQ::from_str(&format!("[[{}/1, 5/2],[{}, -1]]", i64::MAX, i64::MIN)).unwrap();
        let b = MatQ::from_str(&format!("[[-{}, 6/2],[-6, 1]]", i64::MAX)).unwrap();
        let cmp = MatQ::from_str(&format!(
            "[[{}, -1/2],[{}, -2]]",
            2 * (i64::MAX as u64),
            i64::MIN + 6
        ))
        .unwrap();

        a -= b;

        assert_eq!(cmp, a);
    }

    /// Ensure that `sub_assign` works for different matrix dimensions.
    #[test]
    fn matrix_dimensions() {
        let dimensions = [(3, 3), (5, 1), (1, 4)];

        for (nr_rows, nr_cols) in dimensions {
            let mut a = MatQ::identity(nr_rows, nr_cols);
            let b = MatQ::new(nr_rows, nr_cols);

            a -= b;

            assert_eq!(MatQ::identity(nr_rows, nr_cols), a);
        }
    }

    /// Ensure that `sub_assign` is available for all types.
    #[test]
    fn availability() {
        let mut a = MatQ::new(2, 2);
        let b = MatQ::new(2, 2);
        let c = MatZ::new(2, 2);

        a -= &b;
        a -= b;
        a -= &c;
        a -= c;
    }
}

#[cfg(test)]
mod test_sub {
    use super::MatQ;
    use crate::{integer::MatZ, rational::Q};
    use std::str::FromStr;

    /// Testing subtraction for two [`MatQ`]
    #[test]
    fn sub() {
        let a: MatQ = MatQ::from_str("[[1/2, 1, 2],[3/7, 4/7, -5]]").unwrap();
        let b: MatQ = MatQ::from_str("[[1/2, 2, 3/4],[3/7, -4/9, 5]]").unwrap();
        let c: MatQ = a - b;
        assert_eq!(c, MatQ::from_str("[[0, -1, 5/4],[0, 64/63, -10]]").unwrap());
    }

    /// Testing subtraction for two borrowed [`MatQ`]
    #[test]
    fn sub_borrow() {
        let a: MatQ = MatQ::from_str("[[1/2, 1, 2],[3/7, 4/7, -5]]").unwrap();
        let b: MatQ = MatQ::from_str("[[1/2, 2, 3/4],[3/7, -4/9, 5]]").unwrap();
        let c: MatQ = &a - &b;
        assert_eq!(c, MatQ::from_str("[[0, -1, 5/4],[0, 64/63, -10]]").unwrap());
    }

    /// Testing subtraction for borrowed [`MatQ`] and [`MatQ`]
    #[test]
    fn sub_first_borrowed() {
        let a: MatQ = MatQ::from_str("[[1/2, 1, 2],[3/7, 4/7, -5]]").unwrap();
        let b: MatQ = MatQ::from_str("[[1/2, 2, 3/4],[3/7, -4/9, 5]]").unwrap();
        let c: MatQ = &a - b;
        assert_eq!(c, MatQ::from_str("[[0, -1, 5/4],[0, 64/63, -10]]").unwrap());
    }

    /// Testing subtraction for [`MatQ`] and borrowed [`MatQ`]
    #[test]
    fn sub_second_borrowed() {
        let a: MatQ = MatQ::from_str("[[1/2, 1, 2],[3/7, 4/7, -5]]").unwrap();
        let b: MatQ = MatQ::from_str("[[1/2, 2, 3/4],[3/7, -4/9, 5]]").unwrap();
        let c: MatQ = a - &b;
        assert_eq!(c, MatQ::from_str("[[0, -1, 5/4],[0, 64/63, -10]]").unwrap());
    }

    /// Testing subtraction for large numbers
    #[test]
    fn sub_large_numbers() {
        let a: MatQ =
            MatQ::from_str(&format!("[[1, 2, {}],[3, -4, {}]]", i64::MIN, u64::MAX)).unwrap();
        let b: MatQ =
            MatQ::from_str(&format!("[[1, 1, {}],[3, 9, 1/{}]]", i64::MAX, i64::MAX)).unwrap();
        let c: MatQ = a - &b;
        assert_eq!(
            c,
            MatQ::from_str(&format!(
                "[[0, 1, -{}],[0, -13, {}]]",
                u64::MAX,
                Q::from(u64::MAX) - Q::from((1, i64::MAX))
            ))
            .unwrap()
        );
    }

    /// Testing sub_safe
    #[test]
    fn sub_safe() {
        let a: MatQ = MatQ::from_str("[[1/2, 1, 2],[3/7, 4/7, -5]]").unwrap();
        let b: MatQ = MatQ::from_str("[[1/2, 2, 3/4],[3/7, -4/9, 5]]").unwrap();
        let c: MatQ = a.sub_safe(&b).unwrap();
        assert_eq!(c, MatQ::from_str("[[0, -1, 5/4],[0, 64/63, -10]]").unwrap());
    }

    /// Testing sub_safe throws error
    #[test]
    fn sub_safe_is_err() {
        let a: MatQ = MatQ::from_str("[[1, 2],[3, 4]]").unwrap();
        let b: MatQ = MatQ::from_str("[[1, 2, 3],[3, -4, 5]]").unwrap();
        let c: MatQ = MatQ::from_str("[[1, 2, 3]]").unwrap();
        assert!(a.sub_safe(&b).is_err());
        assert!(c.sub_safe(&b).is_err());
    }

    /// Ensure that `sub` is available for all types between [`MatZ`] and [`MatQ`].
    #[test]
    fn availability() {
        let a = MatQ::new(2, 2);
        let b = MatZ::new(2, 2);
        let c = MatQ::new(2, 2);

        let _ = &a - &b;
        let _ = &a - b.clone();
        let _ = a.clone() - &b;
        let _ = a.clone() - b.clone();
        let _ = &b - &a;
        let _ = &b - a.clone();
        let _ = b.clone() - &a;
        let _ = b.clone() - a.clone();

        let _ = &a - &c;
        let _ = &a - c.clone();
        let _ = a.clone() - &c;
        let _ = a.clone() - c.clone();
        let _ = &c - &a;
        let _ = &c - a.clone();
        let _ = c.clone() - &a;
        let _ = c.clone() - a.clone();
    }
}

#[cfg(test)]
mod test_sub_matz {
    use super::MatZ;
    use crate::rational::{MatQ, Q};
    use std::str::FromStr;

    /// Ensures that subtraction between [`MatZ`] and [`MatQ`] works properly incl..
    #[test]
    fn small_numbers() {
        let a = MatZ::from_str("[[1, 2],[3, 4]]").unwrap();
        let b = MatQ::from_str("[[5, 1/2],[2, 10]]").unwrap();
        let cmp = MatQ::from_str("[[4, -3/2],[-1, 6]]").unwrap();

        let res = &b - &a;

        assert_eq!(res, cmp);
    }

    /// Testing subtraction for large numbers.
    #[test]
    fn large_numbers() {
        let a: MatZ = MatZ::from_str(&format!("[[1, 1, {}],[3, 9, 4]]", i64::MIN)).unwrap();
        let b = MatQ::from_str(&format!("[[1, 2, 1/{}],[3, -4, 5]]", i64::MAX)).unwrap();

        let c = &b - a;

        assert_eq!(
            c,
            MatQ::from_str(&format!(
                "[[0, 1, {}],[0, -13, 1]]",
                Q::from((1, i64::MAX)) - Q::from((i64::MIN, 1))
            ))
            .unwrap()
        );
    }

    /// Ensures that subtraction between [`MatZ`] and [`MatQ`] is available for any combination.
    #[test]
    fn available() {
        let a = MatZ::new(2, 2);
        let b = MatQ::new(2, 2);

        let _ = &b - &a;
        let _ = &b - a.clone();
        let _ = b.clone() - &a;
        let _ = b.clone() - a.clone();
    }

    /// Ensures that mismatching rows results in a panic.
    #[test]
    #[should_panic]
    fn mismatching_rows() {
        let a = MatZ::new(3, 2);
        let b = MatQ::new(2, 2);

        let _ = &b - &a;
    }

    /// Ensures that mismatching columns results in a panic.
    #[test]
    #[should_panic]
    fn mismatching_column() {
        let a = MatZ::new(2, 3);
        let b = MatQ::new(2, 2);

        let _ = &b - &a;
    }
}