poulpy/base2k/src/encoding.rs
base2k/src/encoding.rsRaw
1use crate::ffi::znx::znx_zero_i64_ref;
2use crate::znx_base::ZnxLayout;
3use crate::{VecZnx, znx_base::ZnxInfos};
4use itertools::izip;
5use rug::{Assign, Float};
6use std::cmp::min;
7
8pub trait Encoding {
9 /// encode a vector of i64 on the receiver.
10 ///
11 /// # Arguments
12 ///
13 /// * `col_i`: the index of the poly where to encode the data.
14 /// * `log_base2k`: base two negative logarithm decomposition of the receiver.
15 /// * `log_k`: base two negative logarithm of the scaling of the data.
16 /// * `data`: data to encode on the receiver.
17 /// * `log_max`: base two logarithm of the infinity norm of the input data.
18 fn encode_vec_i64(&mut self, col_i: usize, log_base2k: usize, log_k: usize, data: &[i64], log_max: usize);
19
20 /// decode a vector of i64 from the receiver.
21 ///
22 /// # Arguments
23 ///
24 /// * `col_i`: the index of the poly where to encode the data.
25 /// * `log_base2k`: base two negative logarithm decomposition of the receiver.
26 /// * `log_k`: base two logarithm of the scaling of the data.
27 /// * `data`: data to decode from the receiver.
28 fn decode_vec_i64(&self, col_i: usize, log_base2k: usize, log_k: usize, data: &mut [i64]);
29
30 /// decode a vector of Float from the receiver.
31 ///
32 /// # Arguments
33 /// * `col_i`: the index of the poly where to encode the data.
34 /// * `log_base2k`: base two negative logarithm decomposition of the receiver.
35 /// * `data`: data to decode from the receiver.
36 fn decode_vec_float(&self, col_i: usize, log_base2k: usize, data: &mut [Float]);
37
38 /// encodes a single i64 on the receiver at the given index.
39 ///
40 /// # Arguments
41 ///
42 /// * `col_i`: the index of the poly where to encode the data.
43 /// * `log_base2k`: base two negative logarithm decomposition of the receiver.
44 /// * `log_k`: base two negative logarithm of the scaling of the data.
45 /// * `i`: index of the coefficient on which to encode the data.
46 /// * `data`: data to encode on the receiver.
47 /// * `log_max`: base two logarithm of the infinity norm of the input data.
48 fn encode_coeff_i64(&mut self, col_i: usize, log_base2k: usize, log_k: usize, i: usize, data: i64, log_max: usize);
49
50 /// decode a single of i64 from the receiver at the given index.
51 ///
52 /// # Arguments
53 ///
54 /// * `col_i`: the index of the poly where to encode the data.
55 /// * `log_base2k`: base two negative logarithm decomposition of the receiver.
56 /// * `log_k`: base two negative logarithm of the scaling of the data.
57 /// * `i`: index of the coefficient to decode.
58 /// * `data`: data to decode from the receiver.
59 fn decode_coeff_i64(&self, col_i: usize, log_base2k: usize, log_k: usize, i: usize) -> i64;
60}
61
62impl Encoding for VecZnx {
63 fn encode_vec_i64(&mut self, col_i: usize, log_base2k: usize, log_k: usize, data: &[i64], log_max: usize) {
64 encode_vec_i64(self, col_i, log_base2k, log_k, data, log_max)
65 }
66
67 fn decode_vec_i64(&self, col_i: usize, log_base2k: usize, log_k: usize, data: &mut [i64]) {
68 decode_vec_i64(self, col_i, log_base2k, log_k, data)
69 }
70
71 fn decode_vec_float(&self, col_i: usize, log_base2k: usize, data: &mut [Float]) {
72 decode_vec_float(self, col_i, log_base2k, data)
73 }
74
75 fn encode_coeff_i64(&mut self, col_i: usize, log_base2k: usize, log_k: usize, i: usize, value: i64, log_max: usize) {
76 encode_coeff_i64(self, col_i, log_base2k, log_k, i, value, log_max)
77 }
78
79 fn decode_coeff_i64(&self, col_i: usize, log_base2k: usize, log_k: usize, i: usize) -> i64 {
80 decode_coeff_i64(self, col_i, log_base2k, log_k, i)
81 }
82}
83
84fn encode_vec_i64(a: &mut VecZnx, col_i: usize, log_base2k: usize, log_k: usize, data: &[i64], log_max: usize) {
85 let size: usize = (log_k + log_base2k - 1) / log_base2k;
86
87 #[cfg(debug_assertions)]
88 {
89 assert!(
90 size <= a.size(),
91 "invalid argument log_k: (log_k + a.log_base2k - 1)/a.log_base2k={} > a.size()={}",
92 size,
93 a.size()
94 );
95 assert!(col_i < a.cols());
96 assert!(data.len() <= a.n())
97 }
98
99 let data_len: usize = data.len();
100 let log_k_rem: usize = log_base2k - (log_k % log_base2k);
101
102 // Zeroes coefficients of the i-th column
103 (0..a.size()).for_each(|i| unsafe {
104 znx_zero_i64_ref(a.n() as u64, a.at_mut_ptr(col_i, i));
105 });
106
107 // If 2^{log_base2k} * 2^{k_rem} < 2^{63}-1, then we can simply copy
108 // values on the last limb.
109 // Else we decompose values base2k.
110 if log_max + log_k_rem < 63 || log_k_rem == log_base2k {
111 a.at_mut(col_i, size - 1)[..data_len].copy_from_slice(&data[..data_len]);
112 } else {
113 let mask: i64 = (1 << log_base2k) - 1;
114 let steps: usize = min(size, (log_max + log_base2k - 1) / log_base2k);
115 (size - steps..size)
116 .rev()
117 .enumerate()
118 .for_each(|(i, i_rev)| {
119 let shift: usize = i * log_base2k;
120 izip!(a.at_mut(col_i, i_rev).iter_mut(), data.iter()).for_each(|(y, x)| *y = (x >> shift) & mask);
121 })
122 }
123
124 // Case where self.prec % self.k != 0.
125 if log_k_rem != log_base2k {
126 let steps: usize = min(size, (log_max + log_base2k - 1) / log_base2k);
127 (size - steps..size).rev().for_each(|i| {
128 a.at_mut(col_i, i)[..data_len]
129 .iter_mut()
130 .for_each(|x| *x <<= log_k_rem);
131 })
132 }
133}
134
135fn decode_vec_i64(a: &VecZnx, col_i: usize, log_base2k: usize, log_k: usize, data: &mut [i64]) {
136 let size: usize = (log_k + log_base2k - 1) / log_base2k;
137 #[cfg(debug_assertions)]
138 {
139 assert!(
140 data.len() >= a.n(),
141 "invalid data: data.len()={} < a.n()={}",
142 data.len(),
143 a.n()
144 );
145 assert!(col_i < a.cols());
146 }
147 data.copy_from_slice(a.at(col_i, 0));
148 let rem: usize = log_base2k - (log_k % log_base2k);
149 (1..size).for_each(|i| {
150 if i == size - 1 && rem != log_base2k {
151 let k_rem: usize = log_base2k - rem;
152 izip!(a.at(col_i, i).iter(), data.iter_mut()).for_each(|(x, y)| {
153 *y = (*y << k_rem) + (x >> rem);
154 });
155 } else {
156 izip!(a.at(col_i, i).iter(), data.iter_mut()).for_each(|(x, y)| {
157 *y = (*y << log_base2k) + x;
158 });
159 }
160 })
161}
162
163fn decode_vec_float(a: &VecZnx, col_i: usize, log_base2k: usize, data: &mut [Float]) {
164 let size: usize = a.size();
165 #[cfg(debug_assertions)]
166 {
167 assert!(
168 data.len() >= a.n(),
169 "invalid data: data.len()={} < a.n()={}",
170 data.len(),
171 a.n()
172 );
173 assert!(col_i < a.cols());
174 }
175
176 let prec: u32 = (log_base2k * size) as u32;
177
178 // 2^{log_base2k}
179 let base = Float::with_val(prec, (1 << log_base2k) as f64);
180
181 // y[i] = sum x[j][i] * 2^{-log_base2k*j}
182 (0..size).for_each(|i| {
183 if i == 0 {
184 izip!(a.at(col_i, size - i - 1).iter(), data.iter_mut()).for_each(|(x, y)| {
185 y.assign(*x);
186 *y /= &base;
187 });
188 } else {
189 izip!(a.at(col_i, size - i - 1).iter(), data.iter_mut()).for_each(|(x, y)| {
190 *y += Float::with_val(prec, *x);
191 *y /= &base;
192 });
193 }
194 });
195}
196
197fn encode_coeff_i64(a: &mut VecZnx, col_i: usize, log_base2k: usize, log_k: usize, i: usize, value: i64, log_max: usize) {
198 let size: usize = (log_k + log_base2k - 1) / log_base2k;
199
200 #[cfg(debug_assertions)]
201 {
202 assert!(i < a.n());
203 assert!(
204 size <= a.size(),
205 "invalid argument log_k: (log_k + a.log_base2k - 1)/a.log_base2k={} > a.size()={}",
206 size,
207 a.size()
208 );
209 assert!(col_i < a.cols());
210 }
211
212 let log_k_rem: usize = log_base2k - (log_k % log_base2k);
213 (0..a.size()).for_each(|j| a.at_mut(col_i, j)[i] = 0);
214
215 // If 2^{log_base2k} * 2^{log_k_rem} < 2^{63}-1, then we can simply copy
216 // values on the last limb.
217 // Else we decompose values base2k.
218 if log_max + log_k_rem < 63 || log_k_rem == log_base2k {
219 a.at_mut(col_i, size - 1)[i] = value;
220 } else {
221 let mask: i64 = (1 << log_base2k) - 1;
222 let steps: usize = min(size, (log_max + log_base2k - 1) / log_base2k);
223 (size - steps..size)
224 .rev()
225 .enumerate()
226 .for_each(|(j, j_rev)| {
227 a.at_mut(col_i, j_rev)[i] = (value >> (j * log_base2k)) & mask;
228 })
229 }
230
231 // Case where prec % k != 0.
232 if log_k_rem != log_base2k {
233 let steps: usize = min(size, (log_max + log_base2k - 1) / log_base2k);
234 (size - steps..size).rev().for_each(|j| {
235 a.at_mut(col_i, j)[i] <<= log_k_rem;
236 })
237 }
238}
239
240fn decode_coeff_i64(a: &VecZnx, col_i: usize, log_base2k: usize, log_k: usize, i: usize) -> i64 {
241 #[cfg(debug_assertions)]
242 {
243 assert!(i < a.n());
244 assert!(col_i < a.cols())
245 }
246
247 let cols: usize = (log_k + log_base2k - 1) / log_base2k;
248 let data: &[i64] = a.raw();
249 let mut res: i64 = data[i];
250 let rem: usize = log_base2k - (log_k % log_base2k);
251 let slice_size: usize = a.n() * a.size();
252 (1..cols).for_each(|i| {
253 let x = data[i * slice_size];
254 if i == cols - 1 && rem != log_base2k {
255 let k_rem: usize = log_base2k - rem;
256 res = (res << k_rem) + (x >> rem);
257 } else {
258 res = (res << log_base2k) + x;
259 }
260 });
261 res
262}
263
264#[cfg(test)]
265mod tests {
266 use crate::{
267 Encoding, FFT64, Module, VecZnx, VecZnxOps,
268 znx_base::{ZnxInfos, ZnxLayout},
269 };
270 use itertools::izip;
271 use sampling::source::Source;
272
273 #[test]
274 fn test_set_get_i64_lo_norm() {
275 let n: usize = 8;
276 let module: Module<FFT64> = Module::<FFT64>::new(n);
277 let log_base2k: usize = 17;
278 let size: usize = 5;
279 let log_k: usize = size * log_base2k - 5;
280 let mut a: VecZnx = module.new_vec_znx(2, size);
281 let mut source: Source = Source::new([0u8; 32]);
282 let raw: &mut [i64] = a.raw_mut();
283 raw.iter_mut().enumerate().for_each(|(i, x)| *x = i as i64);
284 (0..a.cols()).for_each(|col_i| {
285 let mut have: Vec<i64> = vec![i64::default(); n];
286 have.iter_mut()
287 .for_each(|x| *x = (source.next_i64() << 56) >> 56);
288 a.encode_vec_i64(col_i, log_base2k, log_k, &have, 10);
289 let mut want: Vec<i64> = vec![i64::default(); n];
290 a.decode_vec_i64(col_i, log_base2k, log_k, &mut want);
291 izip!(want, have).for_each(|(a, b)| assert_eq!(a, b, "{} != {}", a, b));
292 });
293 }
294
295 #[test]
296 fn test_set_get_i64_hi_norm() {
297 let n: usize = 8;
298 let module: Module<FFT64> = Module::<FFT64>::new(n);
299 let log_base2k: usize = 17;
300 let size: usize = 5;
301 let log_k: usize = size * log_base2k - 5;
302 let mut a: VecZnx = module.new_vec_znx(2, size);
303 let mut source = Source::new([0u8; 32]);
304 let raw: &mut [i64] = a.raw_mut();
305 raw.iter_mut().enumerate().for_each(|(i, x)| *x = i as i64);
306 (0..a.cols()).for_each(|col_i| {
307 let mut have: Vec<i64> = vec![i64::default(); n];
308 have.iter_mut().for_each(|x| *x = source.next_i64());
309 a.encode_vec_i64(col_i, log_base2k, log_k, &have, 64);
310 let mut want = vec![i64::default(); n];
311 a.decode_vec_i64(col_i, log_base2k, log_k, &mut want);
312 izip!(want, have).for_each(|(a, b)| assert_eq!(a, b, "{} != {}", a, b));
313 })
314 }
315}