arnaucube
arnaucube/poulpyPublic Self-hosted repository
poulpy/math/tests/rescaling_rns.rs
math/tests/rescaling_rns.rsRaw
 1use math::poly::PolyRNS;
 2use math::ring::impl_u64::ring_rns::new_rings;
 3use math::ring::{Ring, RingRNS};
 4use num_bigint::BigInt;
 5use num_bigint::Sign;
 6use sampling::source::Source;
 7
 8#[test]
 9fn rescaling_rns_u64() {
10    let n = 1 << 10;
11    let moduli: Vec<u64> = vec![0x1fffffffffc80001u64, 0x1fffffffffe00001u64];
12    let rings: Vec<Ring<u64>> = new_rings(n, moduli);
13    let ring_rns: RingRNS<'_, u64> = RingRNS::new(&rings);
14
15    test_div_floor_by_last_modulus::<false>(&ring_rns);
16    test_div_floor_by_last_modulus::<true>(&ring_rns);
17}
18
19fn test_div_floor_by_last_modulus<const NTT: bool>(ring_rns: &RingRNS<u64>) {
20    let seed: [u8; 32] = [0; 32];
21    let mut source: Source = Source::new(seed);
22
23    let mut a: PolyRNS<u64> = ring_rns.new_polyrns();
24    let mut b: PolyRNS<u64> = ring_rns.new_polyrns();
25    let mut c: PolyRNS<u64> = ring_rns.at_level(ring_rns.level() - 1).new_polyrns();
26
27    // Allocates a random PolyRNS
28    ring_rns.fill_uniform(&mut source, &mut a);
29
30    // Maps PolyRNS to [BigInt]
31    let mut coeffs_a: Vec<BigInt> = (0..a.n()).map(|i| BigInt::from(i)).collect();
32    ring_rns
33        .at_level(a.level())
34        .to_bigint_inplace(&a, 1, &mut coeffs_a);
35
36    // Performs c = intt(ntt(a) / q_level)
37    if NTT {
38        ring_rns.ntt_inplace::<false>(&mut a);
39    }
40
41    ring_rns.div_floor_by_last_modulus::<NTT>(&a, &mut b, &mut c);
42
43    if NTT {
44        ring_rns.at_level(c.level()).intt_inplace::<false>(&mut c);
45    }
46
47    // Exports c to coeffs_c
48    let mut coeffs_c = vec![BigInt::from(0); c.n()];
49    ring_rns
50        .at_level(c.level())
51        .to_bigint_inplace(&c, 1, &mut coeffs_c);
52
53    // Performs floor division on a
54    let scalar_big = BigInt::from(ring_rns.0[ring_rns.level()].modulus.q);
55    coeffs_a.iter_mut().for_each(|a| {
56        // Emulates floor division in [0, q-1] and maps to [-(q-1)/2, (q-1)/2-1]
57        *a /= &scalar_big;
58        if a.sign() == Sign::Minus {
59            *a -= 1;
60        }
61    });
62
63    assert!(coeffs_a == coeffs_c);
64}