qfall-math 0.2.0

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
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
// Copyright 2023 Jan Niklas Siemer
//
// 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/>.

//! This module contains algorithms for sampling according to the discrete Gaussian distribution.

use crate::{
    error::MathError,
    integer::MatZ,
    macros::seeded::seedable_function,
    rational::{MatQ, Q},
    traits::{MatrixDimensions, MatrixSetEntry},
    utils::sample::discrete_gauss::{
        DiscreteGaussianIntegerSampler, LookupTableSetting, TAILCUT, sample_d,
        sample_d_precomputed_gso,
    },
    utils::sample::uniform::SamplerRng,
};
use std::fmt::Display;

impl MatZ {
    seedable_function!(
        /// Initializes a new matrix with dimensions `num_rows` x `num_columns` and with each entry
        /// sampled independently according to the discrete Gaussian distribution,
        /// using [`Z::sample_discrete_gauss`](crate::integer::Z::sample_discrete_gauss).
        ///
        /// Parameters:
        /// - `num_rows`: specifies the number of rows the new matrix should have
        /// - `num_cols`: specifies the number of columns the new matrix should have
        /// - `center`: specifies the positions of the center with peak probability
        /// - `s`: specifies the Gaussian parameter, which is proportional
        ///   to the standard deviation `sigma * sqrt(2 * pi) = s`
        #[seeded]
        /// - `seed`: specifies the 256-bit seed of the PRNG used for sampling
        #[optionally_seeded]
        /// - `seed`: specifies an optional 256-bit seed of the PRNG used for sampling.
        #[optionally_seeded]
        ///   If `None` is provided, a fresh [`ThreadRng`](rand::rngs::ThreadRng) is used instead.
        ///
        /// Returns a matrix with each entry sampled independently from the
        /// specified discrete Gaussian distribution or an error if `s < 0`.
        ///
        /// # Examples
        /// ```
        /// use qfall_math::integer::MatZ;
        ///
        #[unseeded]
        /// let sample = MatZ::sample_discrete_gauss(3, 1, 0, 1.25f32).unwrap();
        #[seeded]
        /// let sample = MatZ::sample_discrete_gauss_seeded(3, 1, 0, 1.25f32, [42; 32]).unwrap();
        /// ```
        ///
        /// # Errors and Failures
        /// - Returns a [`MathError`] of type [`InvalidIntegerInput`](MathError::InvalidIntegerInput)
        ///   if `s < 0`.
        ///
        /// # Panics ...
        /// - if the provided number of rows and columns are not suited to create a matrix.
        ///   For further information see [`MatZ::new`].
        pub(crate) fn sample_discrete_gauss(
            num_rows: impl TryInto<i64> + Display,
            num_cols: impl TryInto<i64> + Display,
            center: impl Into<Q>,
            s: impl Into<Q>,
            seed: Option<[u8; 32]>,
        ) -> Result<MatZ, MathError> {
            let mut out = Self::new(num_rows, num_cols);

            let mut dgis = DiscreteGaussianIntegerSampler::init(
                center,
                s,
                unsafe { TAILCUT },
                LookupTableSetting::FillOnTheFly,
                seed,
            )?;

            for row in 0..out.get_num_rows() {
                for col in 0..out.get_num_columns() {
                    let sample = dgis.sample_z();
                    unsafe { out.set_entry_unchecked(row, col, sample) };
                }
            }

            Ok(out)
        }
    );

    seedable_function!(
        /// SampleD samples a discrete Gaussian from the lattice with a provided `basis`.
        ///
        /// We do not check whether `basis` is actually a basis. Hence, the callee is
        /// responsible for making sure that `basis` provides a suitable basis.
        ///
        /// Parameters:
        /// - `basis`: specifies a basis for the lattice from which is sampled
        /// - `n`: specifies the range from which [`Z::sample_discrete_gauss`](crate::integer::Z::sample_discrete_gauss) samples
        /// - `center`: specifies the positions of the center with peak probability
        /// - `s`: specifies the Gaussian parameter, which is proportional
        ///   to the standard deviation `sigma * sqrt(2 * pi) = s`
        #[seeded]
        /// - `seed`: specifies the 256-bit seed of the PRNG used for sampling
        #[optionally_seeded]
        /// - `seed`: specifies an optional 256-bit seed of the PRNG used for sampling.
        #[optionally_seeded]
        ///   If `None` is provided, a fresh [`ThreadRng`](rand::rngs::ThreadRng) is used instead.
        ///
        /// Returns a lattice vector sampled according to the discrete Gaussian distribution
        /// or an error if `s < 0`, the number of rows of the `basis` and `center` differ,
        /// or if `center` is not a column vector.
        ///
        /// # Examples
        /// ```
        /// use qfall_math::{integer::MatZ, rational::MatQ};
        /// let basis = MatZ::identity(5, 5);
        /// let center = MatQ::new(5, 1);
        ///
        #[unseeded]
        /// let sample = MatZ::sample_d(&basis, &center, 1.25f32).unwrap();
        #[seeded]
        /// let sample = MatZ::sample_d_seeded(&basis, &center, 1.25f32, [42; 32]).unwrap();
        /// ```
        ///
        /// # Errors and Failures
        /// - Returns a [`MathError`] of type [`InvalidIntegerInput`](MathError::InvalidIntegerInput)
        ///   if `s < 0`.
        /// - Returns a [`MathError`] of type [`MismatchingMatrixDimension`](MathError::MismatchingMatrixDimension)
        ///   if the number of rows of the `basis` and `center` differ.
        /// - Returns a [`MathError`] of type [`StringConversionError`](MathError::StringConversionError)
        ///   if `center` is not a column vector.
        ///
        /// This function implements SampleD according to:
        /// - \[1\] Gentry, Craig and Peikert, Chris and Vaikuntanathan, Vinod (2008).
        ///   Trapdoors for hard lattices and new cryptographic constructions.
        ///   In: Proceedings of the fortieth annual ACM symposium on Theory of computing.
        ///   <https://dl.acm.org/doi/pdf/10.1145/1374376.1374407>
        pub(crate) fn sample_d(
            basis: &MatZ,
            center: &MatQ,
            s: impl Into<Q>,
            seed: Option<[u8; 32]>,
        ) -> Result<Self, MathError> {
            let s: Q = s.into();

            sample_d(basis, center, &s, seed)
        }
    );

    seedable_function!(
        /// Samples a non-spherical discrete Gaussian depending on your choice of
        /// `sigma_sqrt` using the standard basis and center `0`.
        ///
        /// Parameters:
        /// - `sigma_sqrt`: specifies the positive definite Gaussian covariance matrix
        ///   with which the *intermediate* continuous Gaussian is sampled before
        ///   the randomized rounding is applied. Here `sigma_sqrt = sqrt(sigma^2 - r^2*I)`
        ///   where sigma is the target covariance matrix. The root can be computed using
        ///   the [`MatQ::cholesky_decomposition`].
        /// - `r`: specifies the rounding parameter for [`MatQ::randomized_rounding`].
        #[seeded]
        /// - `seed`: specifies the 256-bit seed of the PRNG used for sampling
        #[optionally_seeded]
        /// - `seed`: specifies an optional 256-bit seed of the PRNG used for sampling.
        #[optionally_seeded]
        ///   If `None` is provided, a fresh [`ThreadRng`](rand::rngs::ThreadRng) is used instead.
        ///
        /// Returns a lattice vector sampled according to the discrete Gaussian distribution.
        ///
        /// # Examples
        /// ```
        /// use qfall_math::integer::MatZ;
        /// use qfall_math::rational::{Q, MatQ};
        /// use std::str::FromStr;
        /// use qfall_math::traits::Pow;
        ///
        /// let covariance_matrix = MatQ::from_str("[[100,1],[1,17]]").unwrap();
        /// let r = Q::from(4);
        ///
        /// let sigma_sqrt = covariance_matrix - r.pow(2).unwrap() * MatQ::identity(2, 2);
        ///
        #[unseeded]
        /// let sample = MatZ::sample_d_common_non_spherical(&sigma_sqrt.cholesky_decomposition(), r).unwrap();
        #[seeded]
        /// let sample = MatZ::sample_d_common_non_spherical_seeded(&sigma_sqrt.cholesky_decomposition(), r, [42; 32]).unwrap();
        /// ```
        ///
        /// # Errors and Failures
        /// - Returns a [`MathError`] of type [`InvalidIntegerInput`](MathError::InvalidIntegerInput)
        ///   if the `r < 0`.
        /// - Returns a [`MathError`] of type [`NoSquareMatrix`](MathError::NoSquareMatrix)
        ///   if the matrix is not symmetric.
        ///
        /// This function implements SampleD according to Algorithm 1. in \[2\].
        /// - \[2\] Peikert, Chris.
        ///   "An efficient and parallel Gaussian sampler for lattices.
        ///   In Annual Cryptology Conference, pp. 80-97. Berlin, Heidelberg: Springer
        ///   Berlin Heidelberg, 2010.
        ///   <https://link.springer.com/chapter/10.1007/978-3-642-14623-7_5>
        pub(crate) fn sample_d_common_non_spherical(
            sigma_sqrt: &MatQ,
            r: impl Into<Q>,
            seed: Option<[u8; 32]>,
        ) -> Result<Self, MathError> {
            // derives an independent seed for every call of a seedable function below,
            // see the documentation of `seedable_function` in `src/macros/seeded.rs`
            let mut rng = SamplerRng::new(seed);

            if !sigma_sqrt.is_square() {
                return Err(MathError::NoSquareMatrix("The covariance matrix has to be square, otherwise no discrete Gaussian can be defined.".to_string()));
            }
            let r = r.into();

            // sample a continuous Gaussian centered around `0` in every dimension with
            // gaussian parameter `1`.
            let d_1 = MatQ::sample_gauss_same_center_optionally_seeded(
                sigma_sqrt.get_num_columns(),
                1,
                0,
                1,
                rng.derive_seed(),
            )?;

            // compute a continuous Gaussian centered around `0` in every dimension with
            // covariance matrix `b_2` (the cholesky decomposition we computed)
            let x_2 = sigma_sqrt * d_1;

            // perform randomized rounding
            x_2.randomized_rounding_optionally_seeded(r, rng.derive_seed())
        }
    );

    seedable_function!(
        /// SampleD samples a discrete Gaussian from the lattice with a provided `basis`.
        ///
        /// We do not check whether `basis` is actually a basis or whether `basis_gso` is
        /// actually the gso of `basis`. Hence, the callee is responsible for making sure
        /// that `basis` provides a suitable basis and `basis_gso` is a corresponding GSO.
        ///
        /// Parameters:
        /// - `basis`: specifies a basis for the lattice from which is sampled
        /// - `basis_gso`: specifies the precomputed gso for `basis`
        /// - `center`: specifies the positions of the center with peak probability
        /// - `s`: specifies the Gaussian parameter, which is proportional
        ///   to the standard deviation `sigma * sqrt(2 * pi) = s`
        #[seeded]
        /// - `seed`: specifies the 256-bit seed of the PRNG used for sampling
        #[optionally_seeded]
        /// - `seed`: specifies an optional 256-bit seed of the PRNG used for sampling.
        #[optionally_seeded]
        ///   If `None` is provided, a fresh [`ThreadRng`](rand::rngs::ThreadRng) is used instead.
        ///
        /// Returns a lattice vector sampled according to the discrete Gaussian distribution
        /// or an error if `s < 0`, the number of rows of the `basis` and `center` differ,
        /// or if `center` is not a column vector.
        ///
        /// # Examples
        /// ```
        /// use qfall_math::{integer::MatZ, rational::MatQ};
        /// let basis = MatZ::identity(5, 5);
        /// let center = MatQ::new(5, 1);
        /// let basis_gso = MatQ::from(&basis).gso();
        ///
        #[unseeded]
        /// let sample = MatZ::sample_d_precomputed_gso(&basis, &basis_gso, &center, 1.25f32).unwrap();
        #[seeded]
        /// let sample = MatZ::sample_d_precomputed_gso_seeded(&basis, &basis_gso, &center, 1.25f32, [42; 32]).unwrap();
        /// ```
        ///
        /// # Errors and Failures
        /// - Returns a [`MathError`] of type [`InvalidIntegerInput`](MathError::InvalidIntegerInput)
        ///   if `s < 0`.
        /// - Returns a [`MathError`] of type [`MismatchingMatrixDimension`](MathError::MismatchingMatrixDimension)
        ///   if the number of rows of the `basis` and `center` differ.
        /// - Returns a [`MathError`] of type [`StringConversionError`](MathError::StringConversionError)
        ///   if `center` is not a column vector.
        ///
        /// # Panics ...
        /// - if the number of rows/columns of `basis_gso` and `basis` mismatch.
        ///
        /// This function implements SampleD according to:
        /// - \[1\] Gentry, Craig and Peikert, Chris and Vaikuntanathan, Vinod (2008).
        ///   Trapdoors for hard lattices and new cryptographic constructions.
        ///   In: Proceedings of the fortieth annual ACM symposium on Theory of computing.
        ///   <https://dl.acm.org/doi/pdf/10.1145/1374376.1374407>
        pub(crate) fn sample_d_precomputed_gso(
            basis: &MatZ,
            basis_gso: &MatQ,
            center: &MatQ,
            s: impl Into<Q>,
            seed: Option<[u8; 32]>,
        ) -> Result<Self, MathError> {
            let s: Q = s.into();

            sample_d_precomputed_gso(basis, basis_gso, center, &s, seed)
        }
    );
}

#[cfg(test)]
mod test_sample_discrete_gauss {
    use crate::utils::sample::test_seed;
    use crate::{
        integer::{MatZ, Z},
        rational::Q,
    };

    // This function only allows for a broader availability, which is tested here.

    /// Checks whether `sample_discrete_gauss` is available for all types
    /// implementing [`Into<Z>`], i.e. u8, u16, u32, u64, i8, ...
    /// or [`Into<Q>`], i.e. u8, i16, f32, Z, Q, ...
    #[test]
    fn availability() {
        for seeded in [false, true] {
            let n = Z::from(1024);
            let center = Q::ZERO;
            let s = Q::ONE;

            let _ = MatZ::sample_discrete_gauss_optionally_seeded(
                2u64,
                3i8,
                &center,
                1u16,
                seeded.then(test_seed),
            );
            let _ = MatZ::sample_discrete_gauss_optionally_seeded(
                3u8,
                2i16,
                &center,
                1u8,
                seeded.then(test_seed),
            );
            let _ = MatZ::sample_discrete_gauss_optionally_seeded(
                1,
                1,
                &center,
                1u32,
                seeded.then(test_seed),
            );
            let _ = MatZ::sample_discrete_gauss_optionally_seeded(
                1,
                1,
                &center,
                1u64,
                seeded.then(test_seed),
            );
            let _ = MatZ::sample_discrete_gauss_optionally_seeded(
                1,
                1,
                &center,
                1i64,
                seeded.then(test_seed),
            );
            let _ = MatZ::sample_discrete_gauss_optionally_seeded(
                1,
                1,
                &center,
                1i32,
                seeded.then(test_seed),
            );
            let _ = MatZ::sample_discrete_gauss_optionally_seeded(
                1,
                1,
                &center,
                1i16,
                seeded.then(test_seed),
            );
            let _ = MatZ::sample_discrete_gauss_optionally_seeded(
                1,
                1,
                &center,
                1i8,
                seeded.then(test_seed),
            );
            let _ = MatZ::sample_discrete_gauss_optionally_seeded(
                1,
                1,
                &center,
                1i64,
                seeded.then(test_seed),
            );
            let _ = MatZ::sample_discrete_gauss_optionally_seeded(
                1,
                1,
                &center,
                &n,
                seeded.then(test_seed),
            );
            let _ = MatZ::sample_discrete_gauss_optionally_seeded(
                1,
                1,
                &center,
                &s,
                seeded.then(test_seed),
            );
            let _ =
                MatZ::sample_discrete_gauss_optionally_seeded(1, 1, 1, &s, seeded.then(test_seed));
            let _ = MatZ::sample_discrete_gauss_optionally_seeded(
                1,
                1,
                2.25,
                &s,
                seeded.then(test_seed),
            );
            let _ = MatZ::sample_discrete_gauss_optionally_seeded(
                1,
                1,
                &center,
                1.25f64,
                seeded.then(test_seed),
            );
            let _ = MatZ::sample_discrete_gauss_optionally_seeded(
                1,
                1,
                &center,
                15.75f32,
                seeded.then(test_seed),
            );

            // explicitly checks the existence of the unseeded and the seeded function
            if seeded {
                let _ = MatZ::sample_discrete_gauss_seeded(2u64, 3i8, &center, 1u16, test_seed());
            } else {
                let _ = MatZ::sample_discrete_gauss(2u64, 3i8, &center, 1u16);
            }
        }
    }

    /// Checks whether the same seed results in the same sample.
    #[test]
    fn same_seed_same_sample() {
        use crate::integer::MatZ;
        let sample_0 = MatZ::sample_discrete_gauss_seeded(3, 1, 0, 1.25f32, [42; 32]).unwrap();
        let sample_1 = MatZ::sample_discrete_gauss_seeded(3, 1, 0, 1.25f32, [42; 32]).unwrap();

        assert_eq!(sample_0, sample_1);
    }

    /// Checks whether the seeded variant outputs the known sample for a fixed seed.
    #[test]
    fn known_answer() {
        use crate::integer::MatZ;
        let sample = MatZ::sample_discrete_gauss_seeded(3, 1, 0, 1.25f32, [42; 32]).unwrap();

        assert_eq!("[[1],[-1],[0]]", sample.to_string());
    }
}

#[cfg(test)]
mod test_sample_d {
    use crate::utils::sample::test_seed;
    use crate::{
        integer::{MatZ, Z},
        rational::{MatQ, Q},
    };

    // Appropriate inputs were tested in utils and thus omitted here.
    // This function only allows for a broader availability, which is tested here.

    /// Checks whether `sample_d` is available for all types
    /// implementing [`Into<Z>`], i.e. u8, u16, u32, u64, i8, ...
    /// or [`Into<Q>`], i.e. u8, i16, f32, Z, Q, ...
    #[test]
    fn availability() {
        for seeded in [false, true] {
            let basis = MatZ::identity(5, 5);
            let n = Z::from(1024);
            let center = MatQ::new(5, 1);
            let s = Q::ONE;

            let _ = MatZ::sample_d_optionally_seeded(&basis, &center, 1u16, seeded.then(test_seed));
            let _ = MatZ::sample_d_optionally_seeded(&basis, &center, 1u8, seeded.then(test_seed));
            let _ = MatZ::sample_d_optionally_seeded(&basis, &center, 1u32, seeded.then(test_seed));
            let _ = MatZ::sample_d_optionally_seeded(&basis, &center, 1u64, seeded.then(test_seed));
            let _ = MatZ::sample_d_optionally_seeded(&basis, &center, 1i64, seeded.then(test_seed));
            let _ = MatZ::sample_d_optionally_seeded(&basis, &center, 1i32, seeded.then(test_seed));
            let _ = MatZ::sample_d_optionally_seeded(&basis, &center, 1i16, seeded.then(test_seed));
            let _ = MatZ::sample_d_optionally_seeded(&basis, &center, 1i8, seeded.then(test_seed));
            let _ = MatZ::sample_d_optionally_seeded(&basis, &center, 1i64, seeded.then(test_seed));
            let _ = MatZ::sample_d_optionally_seeded(&basis, &center, &n, seeded.then(test_seed));
            let _ = MatZ::sample_d_optionally_seeded(&basis, &center, &s, seeded.then(test_seed));
            let _ =
                MatZ::sample_d_optionally_seeded(&basis, &center, 1.25f64, seeded.then(test_seed));
            let _ =
                MatZ::sample_d_optionally_seeded(&basis, &center, 15.75f32, seeded.then(test_seed));

            // explicitly checks the existence of the unseeded and the seeded function
            if seeded {
                let _ = MatZ::sample_d_seeded(&basis, &center, 1u16, test_seed());
            } else {
                let _ = MatZ::sample_d(&basis, &center, 1u16);
            }
        }
    }

    /// Checks whether `sample_d_precomputed_gso` is available for all types
    /// implementing [`Into<Z>`], i.e. u8, u16, u32, u64, i8, ...
    /// or [`Into<Q>`], i.e. u8, i16, f32, Z, Q, ...
    #[test]
    fn availability_prec_gso() {
        for seeded in [false, true] {
            let basis = MatZ::identity(5, 5);
            let n = Z::from(1024);
            let center = MatQ::new(5, 1);
            let s = Q::ONE;
            let basis_gso = MatQ::from(&basis);

            let _ = MatZ::sample_d_precomputed_gso_optionally_seeded(
                &basis,
                &basis_gso,
                &center,
                1u16,
                seeded.then(test_seed),
            );
            let _ = MatZ::sample_d_precomputed_gso_optionally_seeded(
                &basis,
                &basis_gso,
                &center,
                1u8,
                seeded.then(test_seed),
            );
            let _ = MatZ::sample_d_precomputed_gso_optionally_seeded(
                &basis,
                &basis_gso,
                &center,
                1u32,
                seeded.then(test_seed),
            );
            let _ = MatZ::sample_d_precomputed_gso_optionally_seeded(
                &basis,
                &basis_gso,
                &center,
                1u64,
                seeded.then(test_seed),
            );
            let _ = MatZ::sample_d_precomputed_gso_optionally_seeded(
                &basis,
                &basis_gso,
                &center,
                1i64,
                seeded.then(test_seed),
            );
            let _ = MatZ::sample_d_precomputed_gso_optionally_seeded(
                &basis,
                &basis_gso,
                &center,
                1i32,
                seeded.then(test_seed),
            );
            let _ = MatZ::sample_d_precomputed_gso_optionally_seeded(
                &basis,
                &basis_gso,
                &center,
                1i16,
                seeded.then(test_seed),
            );
            let _ = MatZ::sample_d_precomputed_gso_optionally_seeded(
                &basis,
                &basis_gso,
                &center,
                1i8,
                seeded.then(test_seed),
            );
            let _ = MatZ::sample_d_precomputed_gso_optionally_seeded(
                &basis,
                &basis_gso,
                &center,
                1i64,
                seeded.then(test_seed),
            );
            let _ = MatZ::sample_d_precomputed_gso_optionally_seeded(
                &basis,
                &basis_gso,
                &center,
                &n,
                seeded.then(test_seed),
            );
            let _ = MatZ::sample_d_precomputed_gso_optionally_seeded(
                &basis,
                &basis_gso,
                &center,
                &s,
                seeded.then(test_seed),
            );
            let _ = MatZ::sample_d_precomputed_gso_optionally_seeded(
                &basis,
                &basis_gso,
                &center,
                1.25f64,
                seeded.then(test_seed),
            );
            let _ = MatZ::sample_d_precomputed_gso_optionally_seeded(
                &basis,
                &basis_gso,
                &center,
                15.75f32,
                seeded.then(test_seed),
            );

            // explicitly checks the existence of the unseeded and the seeded function
            if seeded {
                let _ = MatZ::sample_d_precomputed_gso_seeded(
                    &basis,
                    &basis_gso,
                    &center,
                    1u16,
                    test_seed(),
                );
            } else {
                let _ = MatZ::sample_d_precomputed_gso(&basis, &basis_gso, &center, 1u16);
            }
        }
    }

    /// Checks whether the same seed results in the same sample.
    #[test]
    fn same_seed_same_sample_d() {
        use crate::{integer::MatZ, rational::MatQ};
        let basis = MatZ::identity(5, 5);
        let center = MatQ::new(5, 1);
        let sample_0 = MatZ::sample_d_seeded(&basis, &center, 1.25f32, [42; 32]).unwrap();
        let sample_1 = MatZ::sample_d_seeded(&basis, &center, 1.25f32, [42; 32]).unwrap();

        assert_eq!(sample_0, sample_1);
    }

    /// Checks whether the same seed results in the same sample.
    #[test]
    fn same_seed_same_sample_d_precomputed_gso() {
        use crate::{integer::MatZ, rational::MatQ};
        let basis = MatZ::identity(5, 5);
        let center = MatQ::new(5, 1);
        let basis_gso = MatQ::from(&basis).gso();
        let sample_0 =
            MatZ::sample_d_precomputed_gso_seeded(&basis, &basis_gso, &center, 1.25f32, [42; 32])
                .unwrap();
        let sample_1 =
            MatZ::sample_d_precomputed_gso_seeded(&basis, &basis_gso, &center, 1.25f32, [42; 32])
                .unwrap();

        assert_eq!(sample_0, sample_1);
    }

    /// Checks whether the seeded variant outputs the known sample for a fixed seed.
    #[test]
    fn known_answer_d() {
        use crate::{integer::MatZ, rational::MatQ};
        let basis = MatZ::identity(5, 5);
        let center = MatQ::new(5, 1);
        let sample = MatZ::sample_d_seeded(&basis, &center, 1.25f32, [42; 32]).unwrap();

        assert_eq!("[[0],[-1],[0],[0],[0]]", sample.to_string());
    }

    /// Checks whether the seeded variant outputs the known sample for a fixed seed.
    #[test]
    fn known_answer_d_precomputed_gso() {
        use crate::{integer::MatZ, rational::MatQ};
        let basis = MatZ::identity(5, 5);
        let center = MatQ::new(5, 1);
        let basis_gso = MatQ::from(&basis).gso();
        let sample =
            MatZ::sample_d_precomputed_gso_seeded(&basis, &basis_gso, &center, 1.25f32, [42; 32])
                .unwrap();

        assert_eq!("[[0],[-1],[0],[0],[0]]", sample.to_string());
    }
}

#[cfg(test)]
mod test_sample_d_common_non_spherical {
    use crate::utils::sample::test_seed;
    use crate::{
        integer::{MatZ, Z},
        rational::{MatQ, Q},
        traits::{MatrixDimensions, Pow},
    };
    use std::str::FromStr;

    /// Checks whether `sample_d_common_non_spherical` is available for all types
    /// implementing [`Into<Z>`], i.e. u8, u16, u32, u64, i8, ...
    /// or [`Into<Q>`], i.e. u8, i16, f32, Z, Q, ...
    /// or [`Into<MatQ>`], i.e. MatQ, MatZ
    #[test]
    fn availability() {
        for seeded in [false, true] {
            let r = Q::from(8);
            let covariance_matrix = MatQ::from_str("[[100,1],[1,65]]").unwrap();
            let covariance_matrix = (covariance_matrix - r.pow(2).unwrap() * MatQ::identity(2, 2))
                .cholesky_decomposition();

            let _ = MatZ::sample_d_common_non_spherical_optionally_seeded(
                &covariance_matrix,
                8,
                seeded.then(test_seed),
            )
            .unwrap();

            let _ = MatZ::sample_d_common_non_spherical_optionally_seeded(
                &covariance_matrix,
                8_u16,
                seeded.then(test_seed),
            )
            .unwrap();
            let _ = MatZ::sample_d_common_non_spherical_optionally_seeded(
                &covariance_matrix,
                8_u32,
                seeded.then(test_seed),
            )
            .unwrap();
            let _ = MatZ::sample_d_common_non_spherical_optionally_seeded(
                &covariance_matrix,
                8_u64,
                seeded.then(test_seed),
            )
            .unwrap();
            let _ = MatZ::sample_d_common_non_spherical_optionally_seeded(
                &covariance_matrix,
                8_i8,
                seeded.then(test_seed),
            )
            .unwrap();
            let _ = MatZ::sample_d_common_non_spherical_optionally_seeded(
                &covariance_matrix,
                8_i16,
                seeded.then(test_seed),
            )
            .unwrap();
            let _ = MatZ::sample_d_common_non_spherical_optionally_seeded(
                &covariance_matrix,
                8_i32,
                seeded.then(test_seed),
            )
            .unwrap();
            let _ = MatZ::sample_d_common_non_spherical_optionally_seeded(
                &covariance_matrix,
                8_i64,
                seeded.then(test_seed),
            )
            .unwrap();
            let _ = MatZ::sample_d_common_non_spherical_optionally_seeded(
                &covariance_matrix,
                Q::from(8),
                seeded.then(test_seed),
            )
            .unwrap();
            let _ = MatZ::sample_d_common_non_spherical_optionally_seeded(
                &covariance_matrix,
                Z::from(8),
                seeded.then(test_seed),
            )
            .unwrap();
            let _ = MatZ::sample_d_common_non_spherical_optionally_seeded(
                &covariance_matrix,
                8f32,
                seeded.then(test_seed),
            )
            .unwrap();
            let _ = MatZ::sample_d_common_non_spherical_optionally_seeded(
                &covariance_matrix,
                8f64,
                seeded.then(test_seed),
            )
            .unwrap();

            // explicitly checks the existence of the unseeded and the seeded function
            if seeded {
                let _ =
                    MatZ::sample_d_common_non_spherical_seeded(&covariance_matrix, 8, test_seed());
            } else {
                let _ = MatZ::sample_d_common_non_spherical(&covariance_matrix, 8);
            }
        }
    }

    /// Checks whether the function panics if a non-square matrix is provided.
    /// anymore
    #[test]
    fn not_square() {
        for seeded in [false, true] {
            let covariance_matrix = MatQ::from_str("[[100,1,1],[1,64,2]]").unwrap();

            assert!(
                MatZ::sample_d_common_non_spherical_optionally_seeded(
                    &covariance_matrix,
                    8,
                    seeded.then(test_seed)
                )
                .is_err()
            );
        }
    }

    /// Checks whether the function returns an error if `r` is too small.
    #[test]
    fn too_small_parameters() {
        for seeded in [false, true] {
            let covariance_matrix = MatQ::from_str("[[100, 1],[1, 65]]").unwrap();

            assert!(
                MatZ::sample_d_common_non_spherical_optionally_seeded(
                    &covariance_matrix,
                    -1,
                    seeded.then(test_seed)
                )
                .is_err()
            );
        }
    }

    /// Checks whether the dimension of the output matches the provided covariance matrix
    #[test]
    fn correct_dimensions() {
        for seeded in [false, true] {
            let covariance_matrix_1 = MatQ::from_str("[[100,1],[1,65]]").unwrap();
            let covariance_matrix_2 = MatQ::from_str("[[100,1,0],[1,65,0],[0,0,10000]]").unwrap();

            let sample_1 = MatZ::sample_d_common_non_spherical_optionally_seeded(
                &covariance_matrix_1,
                8,
                seeded.then(test_seed),
            )
            .unwrap();
            let sample_2 = MatZ::sample_d_common_non_spherical_optionally_seeded(
                &covariance_matrix_2,
                8,
                seeded.then(test_seed),
            )
            .unwrap();

            assert_eq!(2, sample_1.get_num_rows());
            assert!(sample_1.is_column_vector());
            assert_eq!(3, sample_2.get_num_rows());
            assert!(sample_2.is_column_vector());
        }
    }

    /// Checks whether the same seed results in the same sample.
    #[test]
    fn same_seed_same_sample() {
        use crate::integer::MatZ;
        use crate::rational::{MatQ, Q};
        use crate::traits::Pow;
        use std::str::FromStr;
        let covariance_matrix = MatQ::from_str("[[100,1],[1,17]]").unwrap();
        let r = Q::from(4);
        let sigma_sqrt = covariance_matrix - r.pow(2).unwrap() * MatQ::identity(2, 2);
        let sample_0 = MatZ::sample_d_common_non_spherical_seeded(
            &sigma_sqrt.cholesky_decomposition(),
            &r,
            [42; 32],
        )
        .unwrap();
        let sample_1 = MatZ::sample_d_common_non_spherical_seeded(
            &sigma_sqrt.cholesky_decomposition(),
            &r,
            [42; 32],
        )
        .unwrap();

        assert_eq!(sample_0, sample_1);
    }

    /// Checks whether the seeded variant outputs the known sample for a fixed seed.
    #[test]
    fn known_answer() {
        use crate::integer::MatZ;
        use crate::rational::{MatQ, Q};
        use crate::traits::Pow;
        use std::str::FromStr;
        let covariance_matrix = MatQ::from_str("[[100,1],[1,17]]").unwrap();
        let r = Q::from(4);
        let sigma_sqrt = covariance_matrix - r.pow(2).unwrap() * MatQ::identity(2, 2);
        let sample = MatZ::sample_d_common_non_spherical_seeded(
            &sigma_sqrt.cholesky_decomposition(),
            &r,
            [42; 32],
        )
        .unwrap();

        assert_eq!("[[-19],[1]]", sample.to_string());
    }
}