poulpy_core/layouts/
gglwe_tsk.rs

1use poulpy_hal::{
2    layouts::{Data, DataMut, DataRef, FillUniform, ReaderFrom, WriterTo},
3    source::Source,
4};
5
6use crate::layouts::{
7    Base2K, Degree, Digits, GGLWELayoutInfos, GGLWESwitchingKey, GLWEInfos, LWEInfos, Rank, Rows, TorusPrecision,
8};
9use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
10
11use std::fmt;
12
13#[derive(PartialEq, Eq, Copy, Clone, Debug)]
14pub struct GGLWETensorKeyLayout {
15    pub n: Degree,
16    pub base2k: Base2K,
17    pub k: TorusPrecision,
18    pub rows: Rows,
19    pub digits: Digits,
20    pub rank: Rank,
21}
22
23#[derive(PartialEq, Eq, Clone)]
24pub struct GGLWETensorKey<D: Data> {
25    pub(crate) keys: Vec<GGLWESwitchingKey<D>>,
26}
27
28impl<D: Data> LWEInfos for GGLWETensorKey<D> {
29    fn n(&self) -> Degree {
30        self.keys[0].n()
31    }
32
33    fn base2k(&self) -> Base2K {
34        self.keys[0].base2k()
35    }
36
37    fn k(&self) -> TorusPrecision {
38        self.keys[0].k()
39    }
40
41    fn size(&self) -> usize {
42        self.keys[0].size()
43    }
44}
45
46impl<D: Data> GLWEInfos for GGLWETensorKey<D> {
47    fn rank(&self) -> Rank {
48        self.keys[0].rank_out()
49    }
50}
51
52impl<D: Data> GGLWELayoutInfos for GGLWETensorKey<D> {
53    fn rank_in(&self) -> Rank {
54        self.rank_out()
55    }
56
57    fn rank_out(&self) -> Rank {
58        self.keys[0].rank_out()
59    }
60
61    fn digits(&self) -> Digits {
62        self.keys[0].digits()
63    }
64
65    fn rows(&self) -> Rows {
66        self.keys[0].rows()
67    }
68}
69
70impl LWEInfos for GGLWETensorKeyLayout {
71    fn n(&self) -> Degree {
72        self.n
73    }
74
75    fn base2k(&self) -> Base2K {
76        self.base2k
77    }
78
79    fn k(&self) -> TorusPrecision {
80        self.k
81    }
82}
83
84impl GLWEInfos for GGLWETensorKeyLayout {
85    fn rank(&self) -> Rank {
86        self.rank_out()
87    }
88}
89
90impl GGLWELayoutInfos for GGLWETensorKeyLayout {
91    fn rank_in(&self) -> Rank {
92        self.rank
93    }
94
95    fn digits(&self) -> Digits {
96        self.digits
97    }
98
99    fn rank_out(&self) -> Rank {
100        self.rank
101    }
102
103    fn rows(&self) -> Rows {
104        self.rows
105    }
106}
107
108impl<D: DataRef> fmt::Debug for GGLWETensorKey<D> {
109    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
110        write!(f, "{self}")
111    }
112}
113
114impl<D: DataMut> FillUniform for GGLWETensorKey<D> {
115    fn fill_uniform(&mut self, log_bound: usize, source: &mut Source) {
116        self.keys
117            .iter_mut()
118            .for_each(|key: &mut GGLWESwitchingKey<D>| key.fill_uniform(log_bound, source))
119    }
120}
121
122impl<D: DataRef> fmt::Display for GGLWETensorKey<D> {
123    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124        writeln!(f, "(GLWETensorKey)",)?;
125        for (i, key) in self.keys.iter().enumerate() {
126            write!(f, "{i}: {key}")?;
127        }
128        Ok(())
129    }
130}
131
132impl GGLWETensorKey<Vec<u8>> {
133    pub fn alloc<A>(infos: &A) -> Self
134    where
135        A: GGLWELayoutInfos,
136    {
137        assert_eq!(
138            infos.rank_in(),
139            infos.rank_out(),
140            "rank_in != rank_out is not supported for GGLWETensorKey"
141        );
142        Self::alloc_with(
143            infos.n(),
144            infos.base2k(),
145            infos.k(),
146            infos.rows(),
147            infos.digits(),
148            infos.rank_out(),
149        )
150    }
151
152    pub fn alloc_with(n: Degree, base2k: Base2K, k: TorusPrecision, rows: Rows, digits: Digits, rank: Rank) -> Self {
153        let mut keys: Vec<GGLWESwitchingKey<Vec<u8>>> = Vec::new();
154        let pairs: u32 = (((rank.0 + 1) * rank.0) >> 1).max(1);
155        (0..pairs).for_each(|_| {
156            keys.push(GGLWESwitchingKey::alloc_with(
157                n,
158                base2k,
159                k,
160                rows,
161                digits,
162                Rank(1),
163                rank,
164            ));
165        });
166        Self { keys }
167    }
168
169    pub fn alloc_bytes<A>(infos: &A) -> usize
170    where
171        A: GGLWELayoutInfos,
172    {
173        assert_eq!(
174            infos.rank_in(),
175            infos.rank_out(),
176            "rank_in != rank_out is not supported for GGLWETensorKey"
177        );
178        let rank_out: usize = infos.rank_out().into();
179        let pairs: usize = (((rank_out + 1) * rank_out) >> 1).max(1);
180        pairs
181            * GGLWESwitchingKey::alloc_bytes_with(
182                infos.n(),
183                infos.base2k(),
184                infos.k(),
185                infos.rows(),
186                infos.digits(),
187                Rank(1),
188                infos.rank_out(),
189            )
190    }
191
192    pub fn alloc_bytes_with(n: Degree, base2k: Base2K, k: TorusPrecision, rows: Rows, digits: Digits, rank: Rank) -> usize {
193        let pairs: usize = (((rank.0 + 1) * rank.0) >> 1).max(1) as usize;
194        pairs * GGLWESwitchingKey::alloc_bytes_with(n, base2k, k, rows, digits, Rank(1), rank)
195    }
196}
197
198impl<D: DataMut> GGLWETensorKey<D> {
199    // Returns a mutable reference to GLWESwitchingKey_{s}(s[i] * s[j])
200    pub fn at_mut(&mut self, mut i: usize, mut j: usize) -> &mut GGLWESwitchingKey<D> {
201        if i > j {
202            std::mem::swap(&mut i, &mut j);
203        };
204        let rank: usize = self.rank_out().into();
205        &mut self.keys[i * rank + j - (i * (i + 1) / 2)]
206    }
207}
208
209impl<D: DataRef> GGLWETensorKey<D> {
210    // Returns a reference to GLWESwitchingKey_{s}(s[i] * s[j])
211    pub fn at(&self, mut i: usize, mut j: usize) -> &GGLWESwitchingKey<D> {
212        if i > j {
213            std::mem::swap(&mut i, &mut j);
214        };
215        let rank: usize = self.rank_out().into();
216        &self.keys[i * rank + j - (i * (i + 1) / 2)]
217    }
218}
219
220impl<D: DataMut> ReaderFrom for GGLWETensorKey<D> {
221    fn read_from<R: std::io::Read>(&mut self, reader: &mut R) -> std::io::Result<()> {
222        let len: usize = reader.read_u64::<LittleEndian>()? as usize;
223        if self.keys.len() != len {
224            return Err(std::io::Error::new(
225                std::io::ErrorKind::InvalidData,
226                format!("self.keys.len()={} != read len={}", self.keys.len(), len),
227            ));
228        }
229        for key in &mut self.keys {
230            key.read_from(reader)?;
231        }
232        Ok(())
233    }
234}
235
236impl<D: DataRef> WriterTo for GGLWETensorKey<D> {
237    fn write_to<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
238        writer.write_u64::<LittleEndian>(self.keys.len() as u64)?;
239        for key in &self.keys {
240            key.write_to(writer)?;
241        }
242        Ok(())
243    }
244}