fhe-study/arith/src/ring_torus.rs
arith/src/ring_torus.rsRaw
1//! π_<N,q>[X] = β_<N,q>[X] / β€_<N,q>[X], polynomials modulo X^N+1 with
2//! coefficients in π_Q.
3//!
4//! Note: this is not an algebraic ring, since internal-product is not well
5//! defined. But since we work over the discrete torus π_q, which we identify as
6//! πq = β€/qβ€ β β€q, whith q=64. Since we allow product between πq elements and
7//! u64, we fit it into the `Ring` trait (from ring.rs) so that we can compose
8//! the π_<N,q> implementation with the other objects from the code.
9
10use rand::{distributions::Distribution, Rng};
11use std::array;
12use std::iter::Sum;
13use std::ops::{Add, AddAssign, Mul, Neg, Sub, SubAssign};
14
15use crate::{ring::Ring, torus::T64, Rq, Zq};
16
17/// π_<N,Q>[X] = π<Q>[X]/(X^N +1), polynomials modulo X^N+1 with coefficients in
18/// π, where Q=2^64.
19#[derive(Clone, Copy, Debug)]
20pub struct Tn<const N: usize>(pub [T64; N]);
21
22impl<const N: usize> Ring for Tn<N> {
23 type C = T64;
24
25 const Q: u64 = u64::MAX; // WIP
26 const N: usize = N;
27
28 fn coeffs(&self) -> Vec<T64> {
29 self.0.to_vec()
30 }
31
32 fn zero() -> Self {
33 Self(array::from_fn(|_| T64::zero()))
34 }
35
36 fn rand(mut rng: impl Rng, dist: impl Distribution<f64>) -> Self {
37 Self(array::from_fn(|_| T64::rand(&mut rng, &dist)))
38 }
39
40 fn from_vec(coeffs: Vec<Self::C>) -> Self {
41 let mut p = coeffs;
42 modulus::<N>(&mut p);
43 Self(array::from_fn(|i| p[i]))
44 }
45
46 fn decompose(&self, beta: u32, l: u32) -> Vec<Self> {
47 let elems: Vec<Vec<T64>> = self.0.iter().map(|r| r.decompose(beta, l)).collect();
48 // transpose it
49 let r: Vec<Vec<T64>> = (0..elems[0].len())
50 .map(|i| (0..elems.len()).map(|j| elems[j][i]).collect())
51 .collect();
52 // convert it to Tn<N>
53 r.iter().map(|a_i| Self::from_vec(a_i.clone())).collect()
54 }
55
56 fn remodule<const P: u64>(&self) -> Tn<N> {
57 todo!()
58 // Rq::<P, N>::from_vec_u64(self.coeffs().iter().map(|m_i| m_i.0).collect())
59 }
60
61 // fn mod_switch<const P: u64>(&self) -> impl Ring {
62 fn mod_switch<const P: u64>(&self) -> Rq<P, N> {
63 // unimplemented!()
64 // TODO WIP
65 let coeffs = array::from_fn(|i| Zq::<P>::from_u64(self.0[i].mod_switch::<P>().0));
66 Rq::<P, N> {
67 coeffs,
68 evals: None,
69 }
70 }
71
72 /// returns [ [(num/den) * self].round() ] mod q
73 /// ie. performs the multiplication and division over f64, and then it rounds the
74 /// result, only applying the mod Q at the end
75 fn mul_div_round(&self, num: u64, den: u64) -> Self {
76 let r: Vec<T64> = self
77 .coeffs()
78 .iter()
79 .map(|e| T64(((num as f64 * e.0 as f64) / den as f64).round() as u64))
80 .collect();
81 Self::from_vec(r)
82 }
83}
84
85impl<const N: usize> Tn<N> {
86 // multiply self by X^-h
87 pub fn left_rotate(&self, h: usize) -> Self {
88 let h = h % N;
89 assert!(h < N);
90 let c = self.0;
91 // c[h], c[h+1], c[h+2], ..., c[n-1], -c[0], -c[1], ..., -c[h-1]
92 // let r: Vec<T64> = vec![c[h..N], c[0..h].iter().map(|&c_i| -c_i).collect()].concat();
93 let r: Vec<T64> = c[h..N]
94 .iter()
95 .copied()
96 .chain(c[0..h].iter().map(|&x| -x))
97 .collect();
98 Self::from_vec(r)
99 }
100
101 pub fn from_vec_u64(v: Vec<u64>) -> Self {
102 let coeffs = v.iter().map(|c| T64(*c)).collect();
103 Self::from_vec(coeffs)
104 }
105}
106
107// apply mod (X^N+1)
108pub fn modulus<const N: usize>(p: &mut Vec<T64>) {
109 if p.len() < N {
110 return;
111 }
112 for i in N..p.len() {
113 p[i - N] = p[i - N].clone() - p[i].clone();
114 p[i] = T64::zero();
115 }
116 p.truncate(N);
117}
118
119impl<const N: usize> Add<Tn<N>> for Tn<N> {
120 type Output = Self;
121
122 fn add(self, rhs: Self) -> Self {
123 Self(array::from_fn(|i| self.0[i] + rhs.0[i]))
124 }
125}
126impl<const N: usize> Add<&Tn<N>> for &Tn<N> {
127 type Output = Tn<N>;
128
129 fn add(self, rhs: &Tn<N>) -> Self::Output {
130 Tn(array::from_fn(|i| self.0[i] + rhs.0[i]))
131 }
132}
133impl<const N: usize> AddAssign for Tn<N> {
134 fn add_assign(&mut self, rhs: Self) {
135 for i in 0..N {
136 self.0[i] += rhs.0[i];
137 }
138 }
139}
140
141impl<const N: usize> Sum<Tn<N>> for Tn<N> {
142 fn sum<I>(iter: I) -> Self
143 where
144 I: Iterator<Item = Self>,
145 {
146 let mut acc = Tn::<N>::zero();
147 for e in iter {
148 acc += e;
149 }
150 acc
151 }
152}
153
154impl<const N: usize> Sub<Tn<N>> for Tn<N> {
155 type Output = Self;
156
157 fn sub(self, rhs: Self) -> Self {
158 Self(array::from_fn(|i| self.0[i] - rhs.0[i]))
159 }
160}
161impl<const N: usize> Sub<&Tn<N>> for &Tn<N> {
162 type Output = Tn<N>;
163
164 fn sub(self, rhs: &Tn<N>) -> Self::Output {
165 Tn(array::from_fn(|i| self.0[i] - rhs.0[i]))
166 }
167}
168
169impl<const N: usize> SubAssign for Tn<N> {
170 fn sub_assign(&mut self, rhs: Self) {
171 for i in 0..N {
172 self.0[i] -= rhs.0[i];
173 }
174 }
175}
176
177impl<const N: usize> Neg for Tn<N> {
178 type Output = Self;
179
180 fn neg(self) -> Self::Output {
181 Tn(array::from_fn(|i| -self.0[i]))
182 }
183}
184
185impl<const N: usize> PartialEq for Tn<N> {
186 fn eq(&self, other: &Self) -> bool {
187 self.0 == other.0
188 }
189}
190
191impl<const N: usize> Mul<Tn<N>> for Tn<N> {
192 type Output = Self;
193
194 fn mul(self, rhs: Self) -> Self {
195 naive_poly_mul(&self, &rhs)
196 }
197}
198impl<const N: usize> Mul<&Tn<N>> for &Tn<N> {
199 type Output = Tn<N>;
200
201 fn mul(self, rhs: &Tn<N>) -> Self::Output {
202 naive_poly_mul(self, rhs)
203 }
204}
205
206fn naive_poly_mul<const N: usize>(poly1: &Tn<N>, poly2: &Tn<N>) -> Tn<N> {
207 let poly1: Vec<u128> = poly1.0.iter().map(|c| c.0 as u128).collect();
208 let poly2: Vec<u128> = poly2.0.iter().map(|c| c.0 as u128).collect();
209 let mut result: Vec<u128> = vec![0; (N * 2) - 1];
210 for i in 0..N {
211 for j in 0..N {
212 result[i + j] = result[i + j] + poly1[i] * poly2[j];
213 }
214 }
215
216 // apply mod (X^N + 1))
217 modulus_u128::<N>(&mut result);
218
219 Tn(array::from_fn(|i| T64(result[i] as u64)))
220}
221fn modulus_u128<const N: usize>(p: &mut Vec<u128>) {
222 if p.len() < N {
223 return;
224 }
225 for i in N..p.len() {
226 // p[i - N] = p[i - N].clone() - p[i].clone();
227 p[i - N] = p[i - N].wrapping_sub(p[i]);
228 p[i] = 0;
229 }
230 p.truncate(N);
231}
232
233impl<const N: usize> Mul<T64> for Tn<N> {
234 type Output = Self;
235 fn mul(self, s: T64) -> Self {
236 Self(array::from_fn(|i| self.0[i] * s))
237 }
238}
239// mul by u64
240impl<const N: usize> Mul<u64> for Tn<N> {
241 type Output = Self;
242 fn mul(self, s: u64) -> Self {
243 Self(array::from_fn(|i| self.0[i] * s))
244 }
245}
246impl<const N: usize> Mul<&u64> for &Tn<N> {
247 type Output = Tn<N>;
248 fn mul(self, s: &u64) -> Self::Output {
249 Tn::<N>(array::from_fn(|i| self.0[i] * *s))
250 }
251}
252
253#[cfg(test)]
254mod tests {
255 use super::*;
256
257 #[test]
258 fn test_left_rotate() {
259 const N: usize = 4;
260 let f = Tn::<N>::from_vec(
261 vec![2i64, 3, -4, -1]
262 .iter()
263 .map(|c| T64(*c as u64))
264 .collect(),
265 );
266
267 // expect f*x^-3 == -1 -2x -3x^2 +4x^3
268 assert_eq!(
269 f.left_rotate(3),
270 Tn::<N>::from_vec(
271 vec![-1i64, -2, -3, 4]
272 .iter()
273 .map(|c| T64(*c as u64))
274 .collect(),
275 )
276 );
277 // expect f*x^-1 == 3 -4x -1x^2 -2x^3
278 assert_eq!(
279 f.left_rotate(1),
280 Tn::<N>::from_vec(
281 vec![3i64, -4, -1, -2]
282 .iter()
283 .map(|c| T64(*c as u64))
284 .collect(),
285 )
286 );
287 }
288}