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