arnaucube
arnaucube/poulpyPublic Self-hosted repository
poulpy/math/src/automorphism.rs
math/src/automorphism.rsRaw
 1use crate::modulus::WordOps;
 2use crate::ring::Ring;
 3use num::Unsigned;
 4use utils::map::Map;
 5
 6pub struct AutoPermMap(Map<usize, AutoPerm>);
 7
 8impl AutoPermMap {
 9    pub fn new() -> Self {
10        Self {
11            0: Map::<usize, AutoPerm>::new(),
12        }
13    }
14
15    pub fn insert(&mut self, perm: AutoPerm) {
16        self.0.insert(perm.gal_el, perm);
17    }
18
19    pub fn gen<O: Unsigned, const NTT: bool>(&mut self, ring: &Ring<O>, gen_1: usize, gen_2: bool) {
20        self.insert(AutoPerm::new::<O, NTT>(ring, gen_1, gen_2))
21    }
22
23    pub fn get(&self, gal_el: &usize) -> Option<&AutoPerm> {
24        self.0.get(gal_el)
25    }
26}
27
28pub struct AutoPerm {
29    pub gal_el: usize,
30    pub permutation: Vec<usize>,
31}
32
33impl AutoPerm {
34    /// Returns a lookup table for the automorphism X^{i} -> X^{i * k mod nth_root}.
35    /// Method will panic if n or nth_root are not power-of-two.
36    /// Method will panic if gal_el is not coprime with nth_root.
37    pub fn new<O: Unsigned, const NTT: bool>(ring: &Ring<O>, gen_1: usize, gen_2: bool) -> Self {
38        let n = ring.n();
39        let cyclotomic_order = ring.cyclotomic_order();
40
41        let gal_el = ring.galois_element(gen_1, gen_2);
42
43        let mut permutation: Vec<usize> = Vec::with_capacity(n);
44
45        if NTT {
46            let mask = cyclotomic_order - 1;
47            let log_cyclotomic_order_half: u32 = cyclotomic_order.log2() as u32 - 1;
48            for i in 0..n {
49                let i_rev: usize = 2 * i.reverse_bits_msb(log_cyclotomic_order_half) + 1;
50                let gal_el_i: usize = ((gal_el * i_rev) & mask) >> 1;
51                permutation.push(gal_el_i.reverse_bits_msb(log_cyclotomic_order_half));
52            }
53        } else {
54            let log_n: usize = n.log2();
55            let mask: usize = (n - 1) as usize;
56            for i in 0..n {
57                let gal_el_i: usize = i as usize * gal_el;
58                let sign: usize = (gal_el_i >> log_n) & 1;
59                let i_out: usize = (gal_el_i & mask) | (sign << (usize::BITS - 1));
60                permutation.push(i_out)
61            }
62        }
63
64        Self {
65            gal_el: gal_el,
66            permutation: permutation,
67        }
68    }
69}